I'm probably missing something easy, but I seem to be blocked here... I have a MySQL database with two tables and each table has several rows. So the goal is to query the database and display the results in a table, so I start like so:
$query = "SELECT name, email, phone FROM users";
Then I have this PHP code:
$result = mysql_query($query);
Then, I use this to get array:
$row = mysql_fetch_array($result);
At this point, I thought I could simply loop through the $row array and display results in a table. I already have a function to do the looping and displaying of the table, but unfortunately the array seems to be incomplete before it even gets to the function.
To troubleshoot this I use this:
for ($i = 0; $i < count($row); $i++) {
echo $row[$i] . " ";
}
At this point, I only get the first row in the database, and there are 3 others that aren't displaying. Any assistance is much appreciated.
You need to use the following because if you call mysql_fetch_array outside of the loop, you're only returning an array of all the elements in the first row. By setting row to a new row returned by mysql_fetch_array each time the loop goes through, you will iterate through each row instead of whats actually inside the row.
while($row = mysql_fetch_array($result))
{
// This will loop through each row, now use your loop here
}
But the good way is to iterate through each row, as you have only three columns
while($row = mysql_fetch_assoc($result))
{
echo $row['name']." ";
echo $row['email']." ";
}
One common way to loop through results is something like this:
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
// do stuff with $row
}
Check out the examples and comments on PHP.net. You can find everything you need to know there.
Related
I need to select multiple comments (if there are any) based on the photo_id. As I understand it you can use the WHERE clause but I'm not exactly sure how to select multiple ones and store them in some kind of array?
e.g.
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
$row = $result->fetch_assoc(); // but there's more than 1 row
If for example $photo1id == 21, how do I get all the comments (2 in this case)? Some kind of while loop?
At the end of the PHP file I have this:
echo json_encode(array('photo1id'=>$photo1id));
I need to store each row in that array somehow because I need to retrieve the data in another PHP file using $.getJSON. Or perhaps there is a better solution to this.
Loop through it and generate an array -
while($row = $result->fetch_assoc()) {
$comments[] = $row;
}
After that you can send the array as json.
echo json_encode($comments);
Is there is more rows, you need to use a loop.
while ($row = $result->fetch_assoc()) {
// your code here
}
Try the code below:
//Run query
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
//While there is a result, fetch it
while($row = $result->fetch_assoc()) {
//Do what you need to do with the comment
}
If you don't want to print the code straight away you can just create an array:
$x=0;
while($row = $result->fetch_assoc()) {
$comment[$x]=$row['comment'];
$x++;
}
I am attempting to loop through rows in MySQL with the following code. Unfortunately, the mysql_fetch_row function is only returning the first row of my query (I confirmed this with print_r). When I use mysql_num_rowsit returns the correct number of rows for that query(2). Any idea why mysql_fetch_row is returning only the first row?
$query = 'SELECT firstName FROM profiles WHERE city="Phoenix" and lastName ="Smith"';
$result = mysql_query($query);
$row = mysql_fetch_row($result);
print_r($row); //This returns only 1 array item: Array ( [0] => John)
$a=mysql_num_rows($result);
print_r($a); //This returns 2
I have also run the same query in MySQL and it returns both rows ("John" and "Jim").
Thanks for the help.
Just perform mysql_fetch_row twice (or in a loop). By definition (if you read the documentation) it returns only one row at once. So:
while ($row = mysql_fetch_row($result)) {
var_dump($row);
}
You want to put it in a while loop:
while ($row = mysql_fetch_array($result)) {
$firstName = $row['firstName'];
echo("$firstName<br />");
}
What this does is for each result (row) it finds, it fetches the data you want and displays it. So it gets the first result, displays the name, loops back to the top, fetches the second result, displays that name and so on, then once you have no more results that match the query criteria, the while loop is ended.
PHP accesses the SQL Results in order of how they're buffered. You'll need to run a loop to access all the contents.
If you wish to load everything into an array:
$allRows=array();
while($row=mysql_fetch_assoc($result) {
$allRows[]=$row;
}
You can use any of the following one:
while ($row = mysql_fetch_array($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_assoc($result))
{
echo $row['firstName'];
}
or
while ($row = mysql_fetch_object($result))
{
echo $row->firstName;
}
I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.
I have got a very simple database and I am getting all rows by this:
while($row = mysql_fetch_array($result)){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:
$name2= $row['name'][2];
Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?
What I am trying to is following:
-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.
If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:
$row = array();
while( $row[] = mysql_fetch_array( $result ) );
Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].
$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
if($row['id'] == 2){
/*You can filtere here*/
}
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
if($counter == 2){
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
}
This While loop will automatically fetch all the records from the database.If you want to get any other field then you will only need to use for this.
Depends on what you want to do. mysql_fetch_array() fetches the current row to which the resource pointer is pointing right now. This means that you don't have $row['name'][2]; at all. On each iteration of the while loop you have all the columns from your query in the $row array, you don't get all rows from the query in the array at once. If you need just this one row, then yes - add a WHERE clause to the query, don't retrieve the other rows if you don't need them. If you need all rows, but you wanna do something special when you get the second row, then you have to add a counter that checks which row you are currently working with. I.e.:
$count = 0;
while($row = mysql_fetch_array($result)){
if(++$count == 2)
{
//do stuff
}
}
Yes, ideally you have to write another sql query to filter your results. If you had :
SELECT * FROM Employes
then you can filter it with :
SELECT * FROM Employes WHERE Name="Paul";
if you want every names that start with a P, you can achieve this with :
SELECT * FROM Employes WHERE Name LIKE "P%";
The main reason to use a sql query to filter your data is that the database manager systems like MySQL/MSSQL/Oracle/etc are highly optimized and they're way faster than a server-side condition block in PHP.
If you want to be able to use 2 consecutive results in one loop, you can store the results of the first loop, and then loop through.
$initial = true;
$storedId = '';
while($row = mysql_fetch_array($result)) {
$storedId = $row['id'];
if($initial) {
$initial = false;
continue;
}
echo $storedId . $row['name'];
}
This only works for consecutive things though.Please excuse the syntax errors, i haven't programmed in PHP for a very long time...
If you always want the second row, no matter how many rows you have in the database you should modify your query thus:
SELECT * FROM theTable LIMIT 1, 1;
See: http://dev.mysql.com/doc/refman/5.5/en/select.html
I used the code from the answer and slightly modified it. Thought I would share.
$result = mysql_query( "SELECT name FROM category;", db_connect() );
$myrow = array();
while ($myrow[] = mysql_fetch_array( $result, MYSQLI_ASSOC )) {}
$num = mysql_num_rows($result);
Example usage
echo "You're viewing " . $myrow[$view_cat]['name'] . "from a total of " . $num;
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
I currently have a database like the picture below.
Where there is a query that selects the rows with number1 equaling 1. When using
mysql_fetch_assoc()
in php I am only given the first is there any way to get the second? Like through a dimesional array like
array['number2'][2]
or something similar
Use repeated calls to mysql_fetch_assoc. It's documented right in the PHP manual.
http://php.net/manual/function.mysql-fetch-assoc.php
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
If you need to, you can use this to build up a multidimensional array for consumption in other parts of your script.
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$i=-1;
while($row = mysqli_fetch_array($Subject))
{
$i++;
$SubjectCode[$i]['SubCode']=$row['SubCode'];
$SubjectCode[$i]['SubLongName']=$row['SubLongName'];
}
Here the while loop will fetch each row.All the columns of the row will be stored in $row variable(array),but when the next iteration happens it will be lost.So we copy the contents of array $row into a multidimensional array called $SubjectCode.contents of each row will be stored in first index of that array.This can be later reused in our script.
(I 'am new to PHP,so if anybody came across this who knows a better way please mention it along with a comment with my name so that I can learn new.)
This is another easy way
$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}
Demo Link
It looks like the complete solution has not been suggested yet
$Query="select SubCode,SubLongName from subjects where sem=1";
$Subject=mysqli_query($con,$Query);
$Rows = array ();
while($row = mysqli_fetch_array($Subject))
{
$Rows [] = $row;
}
The $Rows [] = $row appends the row to the array. The result is a multidimensional array of all rows.