-1

I am trying to grab data from my database and place in a format so I can call field1 and return field2.

In my mind I think this:

while($row = mysqli_fetch_assoc($result)) {
    $aa = $row["field1"];
    $bb = $row["field2"];
}

$cc = array(“$aa”=>”$bb”);

Will compute this:

$cc = array(
    "Row1a"=>"Stuff in field2 row1b",
    "Row2a"=>"Stuff in field2 Row2b",
    "Row3a"=>"Stuff in field2 Row3b",
    "Row4a"=>"Stuff in field2 Row4b",
    );

After this I will be able to:

echo $cc('Row1a');

To display:

Stuff in field2 row1b
2
  • $cc is overwritten each time through the loop so you end up with only the last row fetched. Commented Jun 30, 2015 at 19:08
  • That makes sense thank you Jay. I think I may need to be a bit more thorough in my question. How can the (top) array in the while() function as the the associative array? Commented Jun 30, 2015 at 22:04

2 Answers 2

1

Please try this and let me know if it meets your requirements

<?php

$result=NULL;

while($row = mysqli_fetch_assoc($result)) {
    $aa = $row["field1"];
    $bb = $row["field2"];
    $result[$aa]=$bb;
}

echo $result['Row1a'];

?>

Edited code Then this should meet your requirement

<?php
$search=$_POST['userText'];
$query= "SELECT  * FROM table WHERE field1='".$search."';";

$result=mysql_query($query,$con);
$output=NULL;
if(mysql_num_rows($result)>0) //to check if at least 1 match found
{
    $array=mysql_fetch_array($result);
    $output=$array['field2'];
}
if(isset($output))
    echo $output; // can be returned as needed
else
    echo 'No match found'; 

?>
Sign up to request clarification or add additional context in comments.

3 Comments

Tried this, but the only thing that showed up was ARRAY x10.
Please provide some data format. like table and fields, just to clear up
I want to be able to get text from a form. Check to see if it matches any of the text in the database field 1 row 3 and if it is, I want to be able to return/echo the data content from field 2 row 3. Is this possible?
0

Here's one way. If there aren't an even number of elements in $row then the odd last one will be set to Last. But obviously this overwrites $result each time so you probably want a multidimensional array using a counter and $result[$i] or some such:

foreach(array_chunk($row, 2) as $pair) {
    if(isset($pair[0], $pair[1])) {
        $result[$pair[0]] = $pair[1];
    }
}
if(isset($pair[0])) {
    $result['Last'] = $pair[0];
}

2 Comments

Will this allow me to cycle through my db and return the values in the format of an associative array?
You need to give an example of what you want the result to look like.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.