Reputation: 21
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
Upvotes: -1
Views: 898
Reputation: 426
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';
?>
Upvotes: 1
Reputation: 78994
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];
}
Upvotes: 0