PHP MySQL Database - All rows into Multi-Dimensional Array - php

It's been a long while since I touched PHP so, I just need a refresher of sorts.
I have an HTML form that captures several lines of data (dataA, dataB, dataC & dataD) and inserts them into a database table (dataAll). I will be entering rows upon rows of data into "dataAll". What I'm looking to do is create a display.php page, where the code will take all of the data and place each cell into an array, or the row of an array, for example:
new Array = [["dataA", "dataA", "dataA", "dataA", "dataA"],
["dataB", "dataB", "dataB", "dataB", "dataB"],
["dataC", "dataC", "dataC", "dataC", "dataC"],
["dataD", "dataD", "dataD", "dataD", "dataD"]];
But I cannot remember the syntax on how to perform this task. Any help would be greatly appreciated.
The database is named 'compdata', the table is 'dataAll', and each row is 'dataA', 'dataB', 'dataC', 'dataD'.
Please let me know if I need to supply more information.

Since you asked for All rows, so the simple code for query is written below:
<?php
//after connection to mysql db using mysql_connect()
$sql = "Select dataA, dataB, dataC, dataD from `compdata`.`dataAll`" ;
$result = mysql_query($sql) ;
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_array($result)){
$dataArray[] = $row ;
}
}
echo '<pre>';
print_r($dataArray) ;//you got the desired 2D array with all results
?>

Assuming you are used to the old mysql_xxx functions:
$data = array ();
$result = mysql_query ('select * from dataAll');
while ($row = mysql_fetch_array ($restult, MYSQL_ASSOC))
$data [] = $row;
Result:
$data = array (
0=>array ('col_1'=>'dataA', 'col_2'=>dataB...),
1=>array ('col_1'=>'dataA', 'col_2'=>dataB...)
);
If you only want the numbers and not the column names, use MYSQL_NUM.
However, mysql functions are being replaced with the more generic PDO object so you might want to look into that.
$stmt = $pdo->query ('select * from dataAll');
$result = $pdo->fetchAll (PDO::FETCH_ASSOC); // Or PDO::FECTCH_NUM
Same results as above.

Related

fetch_array() - cannot add multiple array fields to new array

I am trying to return a json from a MySQL query to use it with xCode but I cannot get an array of several objects with multiple fields. I have read the documentation on php.net and over here, but I still can't get it.
1) Let's say I have a MySQL table with 3 rows (for example 3 people). Each row contains 3 fields (lastname, firstname, dateOfBirth):
$result = mysqli_query($mysqli, $sql) // where $sql = "SELECT * FROM tbl_syncList"
$resultArray = array();
while ($row = $result->fetch_array()) {
$resultArray[] = $row["lastname"];
}
echo json_encode($resultArray); // --> return "["Lastname1", "Lastname2"...] - that's okay, I understand I return the value of the key "lastname"
I don't know how to get an array with the entire rows (all the fields at once), like:
[["Firstname1", "Lastname1", "dateOfBirth1"], ["Firstname2", "Lastname2", "dateOfBirth2"],...]
I tried to replace
$resultArray[] = $row["lastname"];
with:
$resultArray[] = $row;
but it just gives the world...
"array"
...with no content. Does anyone have an idea?
Thanks a lot!
Are you sure the array is properly populated to begin with? print_r($resultArray) and see what you have there with = $row (which is correct).

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Catch an array of data and outputting a single row

I need to have a single row of data "printed out" through php.
So, take this example from w3schools:
http://www.w3schools.com/PHP/php_mysql_select.asp
There is a cicle that goes through all the rows ( in this case, 2) and prints them out. The end result is:
Peter Griffin
Glenn Quagmire
What I want is to be able to select row 1 or 2 (or more) and just have that row of data selected. Then I could say something like (I know this doesent work, just an example):
echo $row["Name",2];
And get:
Glenn Quagmire
I believe I have to get a special parameter in mysql_fetch_array, but I cant find it anywhere, and I bet its something really simple. Please help me out, full examples/tutorials/guides links are preferred.
you have 2 options. First is edit your SQL query like exmaple below this will return just 2nd row from database.
$result = mysql_query("SELECT * FROM Persons" WHERE id = 2);
Or during the foreach loop fetch all result into another array.
$result = mysql_query("SELECT * FROM Persons");
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row['FirstName'] . " " . $row['LastName'];
}
As far as i know mysql doesnt have a function to return the entire query as an array.
So you can switch to using PDO (recommended):
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
$result = $sth->fetchAll();
echo $result[1]['name'];
or if you must use the mysql_functions just create an array with the loop:
while($row = mysql_fetch_array($result)) {
$result[] = $row;
}
echo $result[1]['name'];
fetchall the results into an array and print the row you want.

How to roam in SQL query more than one time in PHP

A friend of mine has asked me a question which i do not know how.
The problem is he wants to use a result set of a query more than one time. Whenever he wants.
There is example tables and example output attached.
I will query two times only:
Select * from ornek1_ust
Select * from ornek1_alt
Is it possible to roam in a result set we already have with PHP to have some output like example output. I want to query database with full data for once. Then i want to use it wherever i want whenever i want.
Example Tables:
Example Output:
You'd want to "cache" the results within PHP. To fetch the data, you'd do a simple join query:
SELECT ornek_ust1.isim AS ust, ornek1_alt.ism AS alt
FROM ornek_ust1
JOIN ornek1_alt ON ornek_ust1.id = ornek1_alt.ust_ID
ORDER BY ornek_ust1.isim, ornek1_alt.ism
and within PHP, do something like:
$data = array();
$sql = "SELECT ...";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
$data[$row['ust'][] = $row['alt'];
}
which will build an array that looks like your desired data:
$data = array(
'ust data1' => array(
0 => 'alt data 1'
1 => 'alt data 2'
),
'ust_data2' => ... etc...
)
It sounds like you want to be using mysql_result() to be able to pull out data from a resultset at will.
If you want to loop through the whole dataset and still have it available to loop through again, you can use mysql_data_seek() to set the internal pointer back to the beginning.
Just store the query results in an array....
$sql = "Select * from ornek1_ust";
$results = array();
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$results[] = $row;
}
// Use $results further on in your code

create array from mysql query php

I have a little problem that I don't understand. I have a db that has an owner and type (and more off course). I want to get a list of all the type values that has owner equal to the current user, but I get only two result
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ORDER BY id DESC ";
$result = mysql_query($sql,$con);
print_r(mysql_fetch_array($result));
prints out:
Array ( [0] => 18 [type] => 18 )
and
$sql = "SELECT type FROM cars WHERE owner='".mysql_real_escape_string($_SESSION['username'])."' AND selling='0' ";
prints out:
Array ( [0] => 16 [type] => 16 )
And the result should be something like 19, 19, 18, 17, 16 in an array. Thats all the types that has me as set as owner.
I have got this working now:
for ($x = 0; $x < mysql_num_rows($result); $x++){
$row = mysql_fetch_assoc($result);
echo $row['type'];
}
Here I print out all the values correctly, but I need to create an array with all the values. I though I could use array_push, but there most be a better way of doing it. I thought I would get all the type values with a simple mysql query.
Very often this is done in a while loop:
$types = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['type'];
}
Have a look at the examples in the documentation.
The mysql_fetch_* methods will always get the next element of the result set:
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.
It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:
By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].
THE CORRECT WAY ************************ THE CORRECT WAY
while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows); // pop the last row off, which is an empty row
You do need to iterate through...
$typeArray = array();
$query = "select * from whatever";
$result = mysql_query($query);
if ($result) {
while ($record = mysql_fetch_array($results)) $typeArray[] = $record['type'];
}
while($row = mysql_fetch_assoc($result)) {
echo $row['type'];
}
You could also make life easier using a wrapper, e.g. with ADODb:
$myarray=$db->GetCol("SELECT type FROM cars ".
"WHERE owner=? and selling=0",
array($_SESSION['username']));
A good wrapper will do all your escaping for you too, making things easier to read.
$type_array = array();
while($row = mysql_fetch_assoc($result)) {
$type_array[] = $row['type'];
}
You may want to go look at the SQL Injection article on Wikipedia. Look under the "Hexadecimal Conversion" part to find a small function to do your SQL commands and return an array with the information in it.
https://en.wikipedia.org/wiki/SQL_injection
I wrote the dosql() function because I got tired of having my SQL commands executing all over the place, forgetting to check for errors, and being able to log all of my commands to a log file for later viewing if need be. The routine is free for whoever wants to use it for whatever purpose. I actually have expanded on the function a bit because I wanted it to do more but this basic function is a good starting point for getting the output back from an SQL call.

Categories