I am struggling to understand why while loop not looping through the first query result.
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
$r2 = $stmt2->fetch(PDO::FETCH_ASSOC);
while ($r2 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
I've read this thread but it is OOP. Any suggestions?
You already have fetched the first record by $r1 = $stmt1->fetch(PDO::FETCH_ASSOC);, and fetching the rest in while loop. This should work -
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
That's because you're fetching it twice. Remove the fetch just before while loop.
To something like this,
$pdo = new PDO('connection');
$stmt2 = $pdo->prepare("SELECT user FROM records
ORDER BY date DESC");
$stmt2->execute();
while ($r1 = $stmt2->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td>' . $r1['user'] . '</td></tr>';
}
Related
I am trying to select all records from a table and then output them below, however I am only able to get the most recent output out.
The table structure is Id, Start, End, DistanceDirections and Date
I am using the code below to get them and then output each Start as a H1 on the page. As mentioned I am only getting the last value out not all as I would expect, I have also tried to be more specific which can be seen in the code below that and it didn't have an effect on the result.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Here is the other try:
$sql = "SELECT * FROM `searchdata` WHERE DistanceDirections = 'distance'";
$stmt = $conn->prepare($sql);
$stmt->execute();
foreach($stmt as $row) {
$htmlResult = "<h1>" . $row['Start'] . "</h1>";
}
Is there something simple I am missing?
You're only executing the query, you'll also need to fetch the rows.
$sql = "SELECT * FROM `searchdata`";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
$htmlResult = "";
foreach($result as $row) {
$htmlResult .= "<h1>" . $row['Start'] . "</h1>";
}
echo $htmlResult;
More info:http://php.net/manual/en/pdostatement.fetchall.php
I wonder if anyone can spot what is going wrong here? The first query has been tested and is working because I can print out the $groups array, but the 2nd one will not run. When I hard code the $groups array it runs fine.
require ('mysqli_connect.php'); // Connect to the db.
echo '<p>If no record is shown, this is because you had an incorrect or missing entry in the search form.<br>Click the back button on the browser and try again</p>';
//Coming from another page
$uninum=$_POST['uninum'];
$sname=$_POST['sname'];
$groups = array ( );
$count = count ($groups);
$q1 = "SELECT `groupid` FROM `groups`
WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
for ($i = 0; $i < $count; $i++){
$q = "SELECT participants.sname, participants.uninum,
groups.groupid
FROM participants
INNER JOIN groups ON
participants.uninum = groups.uninum
WHERE groups.groupid ='".$groups[$i]."'";
$result = #mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it ran, display the records.
// Table header.
echo '<table>
<tr>
<td><b>Edit</b></td>
<td><b>Surnname</b></td>
<td><b>University ID</b></td>
<td><b>Group</b></td>
</tr>';
// Fetch and display the records:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr>
<td>Edit</td>
<td>' . $row['sname'] . '</td>
<td>' . $row['uninum'] . '</td>
<td>' . $row['groupid'] . '</td>
</tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($result); // Free up the resources.
echo "<br><br>";
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
}
}
$groups = array ( );
$count = count ($groups);
$count is always equal zero
Try removing # with mysqli_query also $groups array will not start looping until your count is greater then zero.
if you var_dump($count) it will return zero.
$count = count ($groups);
var_dump($count);
You should count array after the query returns result set, right after ending while loop
$q1 = "SELECT `groupid` FROM `groups` WHERE `uninum` = '".$uninum."'";
$result1 = #mysqli_query($dbcon,$q1);
while ($row1 = mysqli_fetch_array ($result1, MYSQLI_ASSOC)){
$groups[] = $row1['groupid'];
}
// count here
$count = count ($groups);
I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.
usually i help people with whatever they need, this time i'm asking for your help.
i'm trying to get a specific row from my database after preforming multiple checkbox select i spend 50 hours on that and i couldn't manage to do that.
each time i'm changing something in my code i get a different ERROR.
i was looking for an answer in every HTML page that exist on the INTERNET !
please show me the light..
here is a part of my form.... value means "size" of the toy
<div class=""><input type="checkbox" name="toys[]" value="6X2" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="4X3" /><label></label></div>
<div class=""><input type="checkbox" name="toys[]" value="8X2.5" /><label></label></div></strike>
here is the PHP code...
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
echo "<table>";
echo "<tr>
<th>ratio</th>
<th>size</th>
<th>built</th>
<th>description</th>
</tr>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
echo "<tr><td>" . $row['ratio'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['built'] .
"</td><td>" . $row['description'] .
"</td></tr>";
echo "</table>";
This is so very far from being valid:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
}
}
$query = $db->query = 'SELECT * FROM `toys` WHERE SIZE = '.$each_check;
More like:
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
$query = $db->query("SELECT * FROM `toys` WHERE SIZE = '".$each_check."'");
}
}
But should be more like:
if (isset($_POST['toys'])) {
$query = 'SELECT * FROM `toys` WHERE SIZE = ?';
$sth = $db->prepare($query);
foreach($_POST['toys'] as $each_check) {
if( ! $sth->execute(array($each_check)) ) {
die('MySQL Error: ' . var_export($sth->error_info(), TRUE);
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
// code here
}
}
}
You're assigning $db->query instead of using it as a function. Change your query line to this:
$query = $db->prepare('SELECT * FROM `toys` WHERE SIZE = :size');
$query->bindValue(':size',$each_check);
$query->execute();
Also, you're going through $_POST['toys'], but not assigning it to any value. I'm guessing you want to add all of your query and table code within the foreach.
if (isset($_POST['toys'])) {
foreach($_POST['toys'] as $each_check) {
// put everything else here
}
}
I want to suggest that you use MySQL's IN (...) clause in your WHERE condition to retrieve all the rows with matching 'size' in just 1 query:
SELECT * FROM toys WHERE size IN ( $chosenSizes )
To get the list of sizes, use PHP's implode function:
$chosenSizes = implode(', ', $_POST['toys']);
You can then use PDO's fetchAll to fetch all rows into a result array.
$resultRows = $sth->fetchAll();
Note: Only use this method when you are quite certain that the result arrays is not too big!
Hagay, the following should work for you:
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'my_name', 'my_pass');
if (isset($_POST['toys'])) {
$sizes = implode(', ', array_map(array($pdo, 'quote'), $_POST['toys']));
$sql = "SELECT * FROM toys WHERE size IN (" . $sizes . ")";
echo '<table>', PHP_EOL;
echo '<tr><th>ratio</th><th>size</th></tr>', PHP_EOL;
foreach( $pdo->query($sql) as $row ) {
echo '<tr><td>', $row['ratio'], '</td><td?', $row['size'], '</td></tr>', PHP_EOL;
}
echo '</table>', PHP_EOL;
}
I have used urldecode to receive a member ID from a previous site. The correct ID is being displayed in the URL but I can't fetch information from the database.
members.php:
<?php
$query = "SELECT name, memberID FROM members";
if(!$result = $db->query($query)){
die('There was an error running your query[' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
?>
profiles.php:
<?php
$id = isset($_GET['memberID']);
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()){
printf("%s (%s)\n", $row["memberID"], $row['name']);
}
}
var_dump($query);
?>
All I get is a blank screen.
I found couple of problems in the code:
members.php
while($row = $result->fetch_assoc()){
printf ('<li>' . $row['name'] . '</li>');
}
Here you are using printf function which have 1st argument for format of string.
Correct that with echo statement as below:
while($row = $result->fetch_assoc()){
echo '<li>' . $row['name'] . '</li>';
}
profiles.php
$id = isset($_GET['memberID']);
Here you are setting the $id with isset() function return value.
You should instead set the value from GET parameter as below:
if(isset($_GET['memberID'])) $id = $_GET['memberID'];
See now if it's working.
Make sure that you use the correct capitalization of memberId vs. memberID. This is very important.
Do not pass values retrieved from GET/POST through urldecode. They already are.
Please try the following based on your code and let us know the results:
<?php
$id = isset($_GET['memberID']) ? $_GET['memberID'] : 0;
if($id > 0){
$query = "SELECT * FROM members WHERE memberID = '".$id."'";
$result = $db->query($query);
if($result){
echo "Rows found: " + $result->num_rows;
} else {
echo "No rows found";
}
} else {
echo "memberID is 0";
}
?>
Is memberID an int field in the database or a string field? If it is an int field then remove the single quotes in your query on profiles.php.