column counterpart to mysql_fetch_array() in PHP - php

I am new to PHP and looking for some help.
I read a column of data from a table in a database and send the data to a dropdown menu in the form of an array.
Now, the function mysql_fetch_array() converts a row of data into an array. I tried using the same function on a column with improper results.
Is there a function that similarly converts a column of data into an array?

You could simple iterate over the result(-rows) and get your column array if you like:
$columnArrays = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
foreach ($row AS $key=>$value){
if (isset($columnArrays[$key]))
$columnArrays[$key][] = $value; //add to existing array
else
$columnArrays[$key] = array($value); //create new array
}
}
Now you have all ids (depending on the column name) in $columnArrays["id"] - all names in $columnArrays["name"] and so on.

Related

How to add resultset rows to a result array as indexed subarrays?

I have a mysqli resultset with two columns of data and several rows. I want to store each row of the resultset as an indexed subarray in my result array (specifically in $rows['data']).
This is my current code:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while ($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
This results in an array that looks like this:
{"name":"Total_watts","data":[1519334969,259,1519335149,246,1519335329,589,1519335509,589,1519335689,341,1519335869,341,1519336050,523,1519336230,662,1519336410,662,1519336590,469]}
But I need the result to be an array that looks like this:
{"name":"Total_watts","data":[1519334969,259],[1519335149,246],[1519335329,589],[1519335509,589],[1519335689,341],[1519335869,341],[1519336050,523],[1519336230,662],[1519336410,662],[1519336590,469]}
Can someone suggest a change in the PHP while loop to produce this output?
You just need to adjust your syntax to place the elements in the same subarray.
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
p.s. Additionally, you could use mysqli_fetch_assoc() since you are only accessing the associative keys. Or even better, use mysqli_fetch_row() and assign the row to your result array.
All baked, it could look like this:
if(!$result=mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings")){
// handle the query error
}else{
$rows=['name'=>'Total_watts'];
while($row=mysqli_fetch_row($result)){
$rows['data'][]=$row; // this will store subarrays like: [1519334969,259]
}
}

How to remove numbers from an 2d array php

I've got an 2d array that stores data from my database table then puts it in a json file. And since I'm not calling my column names because it is dynamic, the array is adding it's incrementation (numbers) automatically with the table cell detail, I don't want this.
Here is the json file example
{"0":"1","Fix":"1","1":"Sunday, May 11, 2014","Date":"Sunday, May 11, 2014","2":"FT","Time":"FT","3":"Cardiff City","Home":"Cardiff City","4":"1-2","Score":"1-2","5":"Chelsea","Away":"Chelsea","6":"Cardiff City Stadium (27,716)","Stadium":"Cardiff City Stadium (27,716)"}
I attempted to remove it in php like this
//Select everything in table
$query = mysql_query("SELECT * FROM ".$tablename);
//Storing the data into one arrays witk the ey => value
while($r=mysql_fetch_array($query)){
//Store the data as a 2d array
$json[] = $r;
}
foreach ($json as $key => $value) {
# code...
if(preg_match('/[0-9]/', $key)){
unset($json[$key]);
}else{
}
}
//Display the JSOn data
$o = fopen($tablename.'.json', 'w');
echo fwrite($o, json_encode($json));
fclose($o);
use MYSQL_ASSOC as a second parameter of the mysql_fetch_array() function.

Looping through resultings record and getting duplicates in foreach

So I am trying what I feel is a simply loop through a record result. My query returns one row of data. I am attempting to simply pull the value of each row from the returning record into a variable called $questions. However, my var $questions when printed out has duplicates in every space. It should read something like Bob|Ted|Joe|Sally and instead it is reading Bob|Bob|Ted|Ted|Joe|Joe|Sally|Sally. Why is the code below running twice in the foreach loop?
while ($row = mssql_fetch_array($result)){
foreach ($row as $col => $value) {
$questions.=$value."|";
}
}
echo "Questions: ".$questions."<br/>";
Here is all you need to do:
$questions = "";
while ($row = mssql_fetch_array($result)){
$questions .= $row['fieldName']."|";
}
echo "Questions: ".$questions."<br/>";
The foreach() in addition to the while() is unnecessary.
The mssql_fetch_array according to PHP doc:
In addition to storing the data in the numeric indices of the result
array, it also stores the data in associative indices, using the field
names as keys.
The result includes a normal array [0...n] with one element for each column, but also an associative array where each value is represented by a key named after the column name.
So if your first column is Id, you could get id from a row in two ways:
$id = $row[0];
# or you could do this
$id = $row['Id'];
This is why you get each value twice when looping through row.

getting correct json response

I am getting data from database and showing it in form of json
Here is how I do:
while ($row = #mysqli_fetch_row($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
which gives result in this form
[["29"],["13702210"],["892344"],["Multi AxleB9RVolvo"],["10:30AM"],["06:45PM"],["14"],["37"],["650"]]
This prints only the database value fetching from table. But this response marked as invalid json response
Each of the fields has name in table.
I want to see json response in this form:;
{"routes":[{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}},{"route":{"routeid":29,"Service_Name":13702210,"Service_Number":892344,"BusType":"Multi AxleB9RVolvo","DepartureTime":"10:30AM","ArravalTime":"06:45PM","available_seats":14,"Total_SeatCapacity":37,"Fare":"650"}}]}
This contains name and nested preview. How can I do this?
I don't know the strucutre of your database, but:
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode(array('routes' => $result1));
May give you the result you want. mysql_fetch_assoc() returns the table rows as associative arrays which will provide keys.
Then array('routes' => $result1) creates a new associative array with the key 'routes' matching your index of arrays.
If they keys aren't correct in your sql response you could try using select field_name as alias_name in your SQL query to return the appropriate field names.
The real trick here is setting up associative arrays with appropriate keys for each value so that json_encode creates objects rather than lists.
You need to use associative array, use this;
while ($row = #mysqli_fetch_assoc($result))
{
array_push($result1,$row);
}
echo $result1 = json_encode($result1,true);
// for `routes` parent
// echo $result1 = json_encode(array("routes" => $result1));

PHP/MySQL: How to get multiple values from a PHP database method

Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>

Categories