Retrieving data from the database - php

Please give me a hand retrieving data from the database and showing it.
I'm learning and this is holding me from advancing :(
I have:
$result = mysql_query($sql);
$num_reg = mysql_num_rows($result);
echo $num_reg; // this shows 3
while($row = mysql_fetch_assoc($result))
{
foreach($row as $value)
{
//Now I need to operate with the rows values.
echo $row['PHONE'];
But this instead of printing the phone numbers, prints them 5 times each
What am I doing wrong?
Thanks a lot

Remove foreach loop
while($row = mysql_fetch_assoc($result))
{
echo $row['PHONE'];
echo $row['NAME'];
echo $row['OTHER_FIELD'];
}

you don't need foreach in that case
while($row = mysql_fetch_assoc($result))
{
echo $row['PHONE'];
}
Probably your $row has 2 elements, and inside foreach your echo $row['PHONE'] is called once for every element

do a print_r($row) in your while loop and a print_r($value) in your foreach loop.
Then ask you why do you echo $row in a loop on $row elements.

You don't need a second foreach() loop inside the while() loop to work on the values. What you're doing here is looping through the rows then looping through the values but if you already have access to the values via the $row variable you don't need to loop again. The fact you get the phone number 5 times suggests you have 5 columns in your table.
An example - remove the foreach() loop:
while($row = mysql_fetch_assoc($result)){
echo $row['PHONE'];
echo $row['NAME'];
echo "<br />";
}
I'm guessing you have a variable called "name" but if not just swap it for one you do have. The last echo just prints a new line to make it easier to read.

Related

Output of mysqli_fetch_array($data) with loop and without loop

When I used while loop to print the values of a particular column using mysqli_fetch_array(), I got the correct output from the database.
while($row=mysqli_fetch_array($data))
{
echo $row['name'];
}
But when I used the below mentioned code without the loop, the output was different.
$row=mysqli_fetch_array($data);
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
When I used the below mentioned code, I could see that I get all the rows in the form of an associative array using mysqli_fetch_array().
$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
while ($row = mysqli_fetch_array($data))
{
$rec[]=$row;
}
echo "<pre>";
print_r($rec);
echo "</pre>";
?>
My question is how to get all the values of a particular column (using a while loop), without usage of any loop.
You can use mysqli_fetch_all to get all data.
Check in php docs
-> mysqli_result::fetch_all -- mysqli_fetch_all —
-> Fetches all result rows as an associative array, a numeric array, or both
First of all, this code:
while($row=mysqli_fetch_array($data))
{
echo $row['name'];
}
is not equivalent to:
$row=mysqli_fetch_array($data);
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
echo $row['name'];
But rather to something like (pseudocode):
$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];
$row = mysqli_fetch_array($data);
if (!$row) return; //break the loop
echo $row['name'];
...
And you could just use multiple mysqli_fetch_array() calls to achieve what you need, but there are other ways to achieve it. One of which is the usage of mysqli_fetch_all(). Both work in a similar way, but mysqli_fetch_all() returns an array of all results you received from the query, rather than one result at a time.
Now, it returns an array of arrays, so to access it, rather than:
$row['name'];
You would need to use:
$row[ROW_NUMBER]['name']
//example
$row[0]['name']
Examples:
1) mysqli_fetch_array()
$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the first row
$row = mysqli_fetch_array($data);
echo $row['name']; //output name from the second row
2) mysqli_fetch_all()
$row = mysqli_fetch_all($data);
echo $row[0]['name']; //output name from the first row
echo $row[1]['name']; //output name from the second row
You can use mysqli_fetch_all to get all data in array but you might need to use foreach for further action.
$con=mysqli_connect("localhost", "root", "", "student_details");
$data=mysqli_query($con,"select * from `registration`");
$row = mysqli_fetch_all($data, MYSQLI_ASSOC);
echo "<pre>"; print_r($row); die;
// Will show all data coming in $row as Array
For further processing, you might need to use foreach like below:
foreach ($row as $item) {
print_r($item); // see what your item contains
}

Display mysql Table without knowing total number of cols in PHP

I need to display mysql table columns without specifying column names in code and I also don't know total number of columns in the table.
Here is my code:
$result = mysqli_query($con,"SELECT * FROM test_table");
echo "<table border='1'>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
foreach ($row as $item){
echo "<td>" . $item . "</td>";
}
echo "</tr>";
}
echo "</table>";
But output is as follows:
i.e values are repeating for each col. Please help me out.
This is because mysqli_fetch_array fetches both an associative array AND a numeric array. Try using mysqli_fetch_assoc or mysqli_fetch_row.
Alternatively, you can specify a parameter in mysqli_fetch_array, like so:
mysqli_fetch_array($result, MYSQLI_ASSOC)
Or
mysqli_fetch_array($result, MYSQLI_NUM)
Change
while($row = mysqli_fetch_array($result))
To
while($row = mysqli_fetch_row($result))

How can I echo this value?

All I need to do is echo array pocket $row[0].
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
}
echo $row[0];
I have googled, but results haven't helped. I know I'm missing something stupid, but I'd appreciate the help!
I'm trying to echo the database column, 'ID'. An example of the data I want to echo would be '3'.
Copy $row[0] as you go.
$lastZero = "";
while ($row = mysqli_result::fetch_array($result)) {
echo '<br>' . $row[1];
$lastZero = $row[0];
}
echo $lastZero;
For debugging the whole row, write this:
var_dump($row)
To output the column ID, write this:
while ($row = mysqli_result::fetch_array($result)) {
var_dump($row); // This will output all values for each row as they're looped through
echo '<br>' . $row['ID'];
}
var_dump($row); // dumps the last row of the returned results, or false if no rows.
echo $row['ID']; // echos the ID of the last row. However if there are no rows, this will not work.
Be aware, as #Daedalus pointed out, $row is an array, so the var_dump line is really just for debugging. Because an array has multiple values, PHP doesn't know how you want to display it. You'll need to program how each element of $row is displayed.

mysql_fetch_array with while loop to echo list of URLs

I have a list of urls that I need to echo from my "menu" table. Here is what I have so far, but I can't seem to figure out the rest of it. The urls below are obviously there to show the format of the original HTML.
<?php
$results = mysql_query("SELECT * FROM menu WHERE level='$level'");
$row = mysql_fetch_array($results);
?>
<li>Achievments</li>
<li>Avatar</li>
.... more urls ....
You need to do it in a loop, usually a while loop:
<?php
$results = mysql_query("SELECT * FROM menu WHERE level='$level'");
while ($row = mysql_fetch_array($results)) {
echo'<li>'.$row['name'].'</li>';
}
?>
I've improvised on your column names (uri and name), they will probably be something different.
Close. Personally I would use put it into a while loop to read all the values. then echo them one by one.
while($row = mysql_fetch_array($results)){
echo "<a href = \"". $row['fieldtouse'] . "\" />". $row['textforlink'] . "<a/>";
}
That is the idea. Loop through results. echo results.
I believe this is a simple case of iterating over the result list. And as you already mentioned you should not use a single mysql_fetch_array, but in a loop like this:
while ($row = mysql_fetch_array($results)) {
print "<li><a href='.../$row[0]' target='evil'>$row[1]</a></li>";
}
Now $row[0] and $row[1] will have to be adapted. Prefer mysql_fetch_assoc to get named result columns, and then apply e.g. $row[url] and $row[title] instead of the numeric keys.

loop through database and show in table

I am trying to loop though my users database to show each username in the table in their own row. I can only get it to show one user but loops through this the number of rows there are. Code is below
<?php
require_once ('../login/connection.php');
include ('functions.php');
$query = "SELECT * FROM users";
$results=mysql_query($query);
$row_count=mysql_num_rows($results);
$row_users = mysql_fetch_array($results);
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
?>
Thanks
mysql_fetch_array fetches a single row - you typically use it in a while loop to eat all the rows in the result set, e.g.
echo "<table>";
while ($row_users = mysql_fetch_array($results)) {
//output a row here
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You're only fetching one row:
$row_users = mysql_fetch_array($results);
You're never calling a fetch again so you're not really looping through anything.
I'd suggest changing your loop to the following:
echo "<table>";
while ($row = mysql_fetch_array($results)) {
echo "<tr><td>".($row['email'])."</td></tr>";
}
echo "</table>";
The while loop will loop through the results and assign a row to $row, until you run out of rows. Plus no need to deal with getting the count of results at that point. This is the "usual" way to loop through results from a DB in php.
In the new MYSQLI, I use this coding
$query = "SELECT * FROM users";
$results=mysqli_query($con,$query);
$row_count=mysqli_num_rows($results);
echo "<table>";
while ($row = mysqli_fetch_array($results)) {
echo "<tr><td>".($row['id'])."</td></tr>";
}
echo "</table>";
mysqli_query($con,$query);
mysqli_close($con);
Your problem is in this line:
echo "<table><tr><td>".($row_users['email'])."</td></tr>";
You're echoing out a <table> tag again. Remove that so your code looks like this:
echo "<table>";
for ($i=0; $i<$row_count; $i++)
{
echo "<tr><td>".($row_users['email'])."</td></tr>";
}
echo "</table>";
You don't need to output a table within a table the way you're doing it.
$result = mysql_query("SELECT `email` FROM `users`");
$num_emails = mysql_num_rows($result);
echo "<table><caption>There are/is $num_emails email(s)</caption>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>{$row['email']}</td></tr>";
}
echo '</table>';
Something like that should work.

Categories