Database Query into Associative Array using PHP - php

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

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';
?>

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];
}

Related

Why is the array is always empty at this point despite the fact that I added data there?

$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.

PHP trying to add values to an array in a while loop

I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.

mysql_query doesn't show all query

I want to show all distinct id_did in cc_did_use
function getdidbycc($cccard_from_sipcard){
$result = mysql_query("SELECT id_did from cc_did_use where id_cc_card='$cccard_from_sipcard'");
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
return $text;
}
I have two id_cc_card="31" and one that value has id_dd="14" and another one = "13"
but result just show first one.
How I can show both of them?
and after that I have another function
function get_did ($p){
$result = mysql_query("SELECT did FROM cc_did WHERE id ='$p'");
while ($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
}
when I run getdidbycc function , it returns two value , 13 and 14 ,
How I can get did numbers from this two values?
You are fetching result and checking in an if condition which will execute only once.
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
You have to fetch the result until there is value in the resultant array. So try with while loop like,
while($row = mysql_fetch_array($result)) // while there are records
{
$text[] = $row['id_did']; // store the result in array $text
}
return $text; // return the array
First of all try to use mysqli or pdo instead of mysql otherwise you will face issues in updated version of php
As per your code $text value is gets over write due to loop so use an array something like this
if ($row = mysql_fetch_array($result)) {
$text[] = $row['id_did'];
}
return $text;
or you can just return complete data as return $row;
if ($row = mysql_fetch_array($result))
{
$text = $row['id_did'];
}
change the above line to this
while($row = mysql_fetch_array($result))
{
echo $row['id_did'].'<br/>';
}
Use a while loop like that : http://php.net/manual/en/function.mysql-fetch-array.php
Mysql fetch array returns the current element only
if ($row = mysql_fetch_array($result))
{
$text[] = $row['id_did'];
}
return $text; // returns both

Searching Array in PHP and return results

Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}

How to index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories