I'm trying to execute a statement where it will show all of the results for each row of my table but all it is doing is showing the results from the last row.
<?php
require_once('php/dbconfig.php');
$stmt = $DB_con->prepare("SELECT * FROM users");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
echo $name[0];
?>
This will work but it will only echo out the name of the last person in my table. If I try to replace the 0 with any other number nothing will show.
I would like to be able to show all users and emails in a list.
In the following block you are assigning each name to the variable $name.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = array($row['user_name']);
$email = array($row['user_email']);
}
I think you intend to either echo $name each iteration of the loop by adding the echo to the loop as:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['user_name'];
$email = $row['user_email'];
echo "{$name} - {$email}";
}
or to add it to an array of names by changing the assignment from $name to $name[] which means 'the next index of the $name array'.
Fetch also returns one record, so you'll need to loop the results or change to fetchAll as suggested by other answers.
Related
I want to fetch data from the database and use the first row initially. Then later if some values are true I want to loop through all of the rows.
The problem is that the while loop starts at the second row.
Is there a way to make the loop start at the first row?
Below is simplified example:
<?php
//GET THE CONNECTION DATA FOR $CONNECTION
require_once('../connect.php');
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
while($data = $get_data->fetch())
{
//STARTS AT THE SECOND ROW BUT NEEDS TO BE THE FIRST ROW
echo $data->last_name;
echo '<br>';
}
Yes you can use fetchAll()
$results = $get_data->fetchAll ();
$data = $results[0];
echo $data->email;
echo '<br>';
foreach($results as $data) {
//...
}
If you need something like this, you are doing something wrong.
For the question stated in the title, Dharman's answer is correct and should be accepted for sake of future visitors.
However, in your particular case, you don't need the first fetch and most likely don't need a while loop.
The first fetch is not needed because it is used to output the data you already have (the email used to query the database).
The while loop is not needed because most likely there is only one record in the database with such email, so you can just echo the username right away.
Either way, a sane version of your code would be either
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => 'john#doe.com']);
$data = $get_data->fetch();
echo $data->email;
echo '<br>';
echo $data->last_name;
echo '<br>';
or (in case your query indeed returns multiple rows)
$email = 'john#doe.com';
$get_data = $connection->prepare('SELECT * FROM db WHERE email = :email');
$get_data -> execute(['email' => $email]);
echo $email;
echo '<br>';
while($data = $get_data->fetch())
{
echo $data->last_name;
echo '<br>';
}
See - you never need to "restart" the while loop.
I am new to the PHP world! Currently practicing MySQL and PHP alone
I want to update my <p> content when my query is completed. But seems like my $name only shows the previous value:
$query = $_GET['query'];
$stmt = $conn->prepare("SELECT * FROM wordList WHERE word = '$query'");
$name = ''; // my variable
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$name == $row['word']; // not working
}
And I am not getting the actual data I want in my HTML:
<p>My name is: <?php echo $name; ?></p>
But getting:
My name is:
Thanks
Try using only one equal to symbol = instead of ==.
$name = $row['word'];
Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);
Trying to figure out how to do this on multiple records. I am trying things out, looking at reference but not understanding how to get it working, firstly here Here is my code that works:
My href link in loop.
city
My PHP
if (isset($_GET['city'])) {
$city = $_GET['city'];
$stmt = $db->prepare("SELECT * from table WHERE city = ? ");
$stmt->execute(array($city));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
} else { //html content }
The above simply pulls city records that are being called via a URL variable in my first loop. What If wanted to repeat this multiple times with different URL Variables to generate different results from the database. So instead of just getting one record like my above code I want to get 2 more, here is a below example of what I mean.
Example Href links in a loop with the URL variables city, name country:
city
name
country
Example of PHP which is not working, but getting these URL variables and passing them through to mysql by SELECT, hopefully you get what I mean):
if (isset($_GET['city'], $_GET['name'], $_GET['country'])) {
$city = $_GET['city'];
$name = $_GET['name'];
$country = $_GET['country'];
$stmt = $db->prepare("SELECT * from table WHERE city = ? OR name = ? OR country = ?");
$stmt->execute(array($city, $name, $country));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
} else { //html content }
Any advice on how to achieve this would be appreciated, also if there is an easier way to do this or my current code is not up to scratch, please let me know. Thanks!
if (isset($_GET['city'])||isset($_GET['name'])||isset($_GET['country'])) {
echo $city= $_GET['city'];
echo $name=$_GET['name'];
echo $country $_GET['country'];
}
I think you're looking to put the url's into an array so that you can use them later? If so, you could do something like this:
if (isset($_GET['city'], $_GET['name'], $_GET['country'])) {
$city = $_GET['city'];
$name = $_GET['name'];
$country = $_GET['country'];
//added:
$url_array = array();
$stmt = $db->prepare("SELECT * from table WHERE city = ? OR name = ? OR country = ?");
$stmt->execute(array($city, $name, $country));
//$row changed to $rows
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)) : //loop starts
//foreach added
foreach($rows as $row){
$url_array[] = $row;
}
} else { //html content }
I hope that helps?
This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
I'm trying to echo out all the rows of a table using PDO but am running into trouble.
With the old way of doing I'd have done it like
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)){
$title= $row['title'];
$body= $row['body'];
}
But with PDO I'm trying;
$result = $db->prepare("SELECT title, body FROM post");
$result->execute();
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
echo $title;
echo $body;
Which keeps giving me Call to undefined method PDO::fetchAll()
Doing the example given in the manual
<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
Works, but I don't think I have control over the individual colums like I would with a $row=['blah']; do I? It also prints out like this; rather ugly:
Array ( [0] => Array ( [title] => This is the test title entered in the database[0]
What needs to be done to properly use PDO to do this?
change:
while ($row = $db->fetchAll(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
to:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
Which keeps giving me Call to undefined method PDO::fetchAll()
This should have given you the hint, that you are using the wrong object. It's PDOStatement::fetchAll as you can see in your second example, or if you want to use it in a while loop PDOStatement::fetch:
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$title = $row['title'];
$body = $row['body'];
}
Additional notes:
$result is a misleading variable name as you might see from the $result->execute() line. You don't execute a result, you execute a statement. This is why in the manual $stmt or $sth (statement handle i guess) are used.
The echo lines should be inside the while loop, otherwise you overwrite again and again, then output only the last row.