Getting the same value while using foreach in PHP - php

I have a row named trailers in a MySQL database and I am querying that table using PHP and storing the result of that query in a variable. After that ,I am using a foreach loop to parse through each value of the variable i.e. each and every trailer value in the table.
But the problem is, when I try to echo the values of the variable only the first value of the variable is getting echoed in place of all other value. This is the query.
$query1 = "SELECT title,img,ratings,star_cast,director,trailer,imdb_ratings,lifetime_collecton,whats_good,whats_bad,watch_or_not
FROM recent_movies";
$result1 = mysqli_query($connect, $query1);
This is the code of the for each loop
<?php
foreach($result1 as $r):
echo $r['trailer'];
endforeach;
?>
Ten same values are getting printed instead of 10 different values.

Use the mysqli_fetch_array function to retrieve rows from a mysqli resultset.
Reference: http://php.net/manual/en/mysqli-result.fetch-array.php
$result1 = mysqli_query($connect, $query1);
while( $row = mysqli_fetch_array($result1,MYSQLI_ASSOC) ) {
echo "<br> " . $row['title'] . " " . $row['ratings'] ;
}

Related

Dynamic HTML image links pulling wrong information from database in PHP

Running XAMPP for Windows 7.2.6. Below is my MariaDB art table from the database.
Code:
<?php
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "SELECT * FROM art LIMIT 50";
$st = $conn->prepare( $sql );
$st->execute();
$row = $st->fetch();
$conn = null;
if (isset($row)) {
echo "row has value";
foreach ($row as $value) {
echo "<a href=\"/admin.php?action=editProducts&product=" . $value[0] . "\"><img src=\"" . $value[2] .
"\" width=\"75\" height=\"75\" title=\"" . $value[6] . "\"></a>";
echo "<br>";
}
}
?>
HTML Image Links when I inspect the source
<img src=" " width="75" height="75" title="c" >
row has value is printing to the browser and I'm seeing in the debugger that the $row array has the proper values. I can't figure out why it's only pulling 1 random character from the art table instead of the proper values, and my error code for each row is:
Notice: Uninitialized string offset: 1
As you are using
$row = $st->fetch();
this is just a single row of data from the table, so then using
foreach ($row as $value) {
just loops across the fields in that 1 row. You need to change it so that the first part retrieves all of the rows in one go using fetchAll()...
$row = $st->fetchAll();
You probably then should change the value to $rows just for semantic purposes (just to say it is a set of rows and not just one row).

mysqli_fetch_row() not displaying after foreach() in PHP

when a foreach is followed by a mysqli_fetch_row displaying the same query results, the mysqli_fetch_row() doesn't display. However if the mysqli_fetch_row is executed before the foreach() both are displayed. Why is this?
QUERY:
<?php
$connection = mysqli_connect("localhost", "root", "", "login_app");
$query = "SELECT *
FROM users";
$result = mysqli_query($connection, $query);
if(!$result){
die("db connection failed " . mysqli_error());
}
?>
ONLY DISPLAYS THE RESULTS OF FOREACH:
<?php
foreach($result as $results){
echo "User ID: " . $results['userID'] . "<br>";
echo "Username: " . $results['userName'] . "<br>";
echo "Password: " . $results['password'] . "<br>";
};
$row = mysqli_fetch_row($result);
print_r($row);
?>
DISPLAYS RESULTS OF BOTH FOREACH AND MYSQLI_FETCH_ROW:
<?php
$row = mysqli_fetch_row($result);
print_r($row);
foreach($result as $results){
echo "User ID: " . $results['userID'] . "<br>";
echo "Username: " . $results['userName'] . "<br>";
echo "Password: " . $results['password'] . "<br>";
};
?>
Executing a SELECT query with mysqli_query returns an mysqli_result object. That object implements Traversable, which is why you're able to use a foreach loop to display the results.
foreach($result as $results){ ...
is basically a handier way of doing
while ($results = mysqli_fetch_row($result)) { ...
(See Example #3 here.)
Either way you do it, you're fetching all the results, and when you get to the end of the result set $results will hold the last value fetched (null).
From the manual:
Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or NULL if there are no more rows.
By iterating the result set with your foreach loop, you are effectively exhausting all of the row which is why no data is available on any subsequent row fetches after the loop.

How to display a single row from a database?

So I have been looking for ways to display data from a database. However, they all require a loop and I do not want a loop as I only have 1 row in this table.
I came across mysqli_fetch_row() but I am not sure how to implement this. I am starting to learn PHP and MySQL and so any help is appreciated! This is what I have so far...
$displayIntro = mysqli_query($connection,"SELECT * FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo $displayTitle['Title'];
echo $displayTitle['Description'];
Also after displaying the plain text, how can I format it with HTML? For example, the title will need to be enclosed in <h1></h1> and the subscription in paragraph <p></p>.
Much thanks to any answers!
The problem is mysqli_fetch_row returns enumerated results, array with numeric indexes, so this should be like:
$displayIntro = mysqli_query($connection,"SELECT `Title`,`Description` FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo $displayTitle[0]; // assuming column 'Title' is first row
echo $displayTitle[1]; // assuming column 'Description' is second row
What you should use here is mysqli_fetch_assoc to fetch a result row as an associative array:
$displayIntro = mysqli_query($connection,"SELECT `Title`,`Description` FROM Introduction");
$displayTitle = mysqli_fetch_assoc($displayIntro);
echo $displayTitle['Title'];
echo $displayTitle['Description'];
Use code from #Maximus2012 answer to form html row. Also to get only one row from table with more than one records you can just add LIMIT 1 at the end of the MySQL query like this:
"SELECT `Title`,`Description` FROM Introduction LIMIT 1"
Hope this helps :)
From PHP manual entry for mysqli_fetch_row (link):
"Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero)." The function returns an enumerated array, not associative array.
Untested, but I would expect this to work:
echo $displayTitle[0];
echo $displayTitle[1];
$displayIntro = mysqli_query($connection,"SELECT * FROM Introduction");
$displayTitle = mysqli_fetch_row($displayIntro);
echo "<html>";
echo "<body>";
echo "<h1>" . $displayTitle['Title'] . "</h1>";
echo "<p>" . $displayTitle['Description'] . "</p>";
echo "</body>";
echo "</html>";

Insert data in a table

I have this code to select and output data from database
<?php
require('system/connect.php'); //load the connection file
$sql = ("SELECT * FROM `movie`"); // add mysql code to a variable. In this case it will select ALL columns from the database.
$query = mysql_query($sql); //run the query contained within the variable.
while ($row = mysql_fetch_array($query)) { //store each single row from the database in an array named $row. While there are any rows left, loop through and execute the following code:
$id = $row['movie_id']; //gets name from DB for a single row
$name = $row['movie_name']; //gets age from DB for a single row
$category = $row['movie_category']; //gets age from DB for a single row
//Following code outputs the data to the webpage:
echo $id;
echo $name;
echo $category;
};
?>
The page show: 1titanicromance2zoroaction3blood diamondsaction
I need a way to make a table or array and to insert data directly to it.
Adding in HTML for Table should do the trick. Although, it's crappy coding to mix PHP and HTML.
<?php
require('system/connect.php'); //load the connection file
$sql = ("SELECT * FROM `movie`"); // add mysql code to a variable. In this case it will select ALL columns from the database.
$query = mysql_query($sql); //run the query contained within the variable.
echo '<table>';
while ($row = mysql_fetch_array($query)) { //store each single row from the database in an array named $row. While there are any rows left, loop through and execute the following code:
$id = $row['movie_id']; //gets name from DB for a single row
$name = $row['movie_name']; //gets age from DB for a single row
$category = $row['movie_category']; //gets age from DB for a single row
//Following code outputs the data to the webpage:
echo '<tr>';
echo '<td>' . $id . '</td>';
echo '<td>' . $name . '</td>';
echo '<td>' . $category . '</td>';
echo '</tr>';
};
echo '</table>';
?>
Did you meant HTML table? Then it will looks like this
<?php
require('system/connect.php'); //load the connection file
$sql = ("SELECT * FROM `movie`"); // add mysql code to a variable. In this case it will select ALL columns from the database.
$query = mysql_query($sql); //run the query contained within the variable.
if (mysql_num_rows($query)) { // if there is some rows in result
echo "<table>"; // starting HTML table
while ($row = mysql_fetch_array($query)) { //loop through the result
echo "<tr>".
"<td>".$row['movie_id']."</td>".
"<td>".$row['movie_name']."</td>".
"<td>".$row['movie_category']."</td>".
"</tr>";
}
echo "</table>";// finishing HTML table
}
?>
NOTE: do not use mysql_* functions. They are deprecated. Use PDO or Mysqli instead.

1st row is not being from database in php

For some reason I'm having a problem retrieving data from my database. It leaves off the first item being listed.
$sql=mysql_query("SELECT * FROM students WHERE (year = '" . mysql_real_escape_string($_SESSION['year']) . "') and ( branch= '" . mysql_real_escape_string(($_SESSION['branch'])). "') ");
$data=mysql_fetch_array( $sql );
print "<table>"
while($data = mysql_fetch_array( $sql ))
{
Print "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td></tr>";
}
print "</table>"
Please help me with this. Thank you.
Remove the following line:
$data=mysql_fetch_array( $sql );
The call to mysql_fetch_array moves the internal pointer to the next row, thus you are getting all rows except the first in your while loop.
You could also reset the internal pointer with mysql_data_seek.
mysql_data_seek ($sql, 0); // 0 for first row
It's because you use mysql_fetch_array one time before your while. The first call will get the first result, and then you will enter into the while loop. the $datavariable will erase the first result to be assigned by the second result and then the third, the fourth and so on.
Because of this call before the while loop, you will always avoid the first result

Categories