PHP: Last data row won't show in pdo GET query [duplicate] - php

This question already has answers here:
MySQL skipping first row
(2 answers)
Closed 5 years ago.
Hi Guys I am trying to get data with pdo from my table but the last inserted row never shows up in the populated table. When I add another row of data then get the data again to populate I then see the data from the row that previously was'nt showing but then the very last inserted row does not show.
Here is my code:
<?php
# This program will allow an admin to see email stats for a certain user
$userid = 1; // admin
$email_to = 2 // employee id
$email_by = 2 // employee id
$sql = "SELECT * FROM users WHERE userid = :user_id AND (person = :email_to OR person = :email_by) ORDER BY date DESC";
$stmt = $this->db->prepare($sql);
$stmt->bindparam(":userid", $userid);
$stmt->bindparam(":email_to", $email_to);
$stmt->bindparam(":email_by", $email_by);
$stmt->execute();
if ($stmt->fetch(PDO::FETCH_ASSOC)) {
echo $stmt->rowCount(); // gives me the expected number of rows
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr><td style="text-align:left;">' . $data['email_subject']
. '</td><td>' . $data['email_date'] . '</td><td>'
. $data['email_time'] . '</td></tr>';
}
} else {
echo "Sorry, no record found.";
}
?>
As commented in the code, the rowCount() does give me the expected number of rows e.g. 10, but in the populated table results I only see 9 rows.
Thanks in advance guys.

It's because you unintentionally skip the first row by the if statement:
if ($stmt->fetch(PDO::FETCH_ASSOC)) { ...
where you assign it to nothing. You may use
do {} while ()
loop instead.

Related

MySQL Select statement not functioning if there are alphabetic characters [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
Expected result:
Loop through all entries in the checkedout table, and select the entry from the game table where the barcode field is the same.
Actual behaviour / issue:
For the most part, this is working as intended. If I set the barcode field to a numerical value in the game table, and then "checkout" that barcode, everything works as intended. The barcodes I'll be using are in the format of ABC12345678. Once I change the values in the barcode field, in the game table to the alphanumeric version, it no longer runs the secondary select statement and displays this error: Fatal error: Call to a member function fetch_assoc() on boolean which refers to the following line: while ($row2 = $result2->fetch_assoc()) {
Oddly enough, if I run the exact same select statement SELECT * FROM game WHERE barcode = 'ABC12345678' on the MySQL instance, it returns the proper results.
Question
Do I need to be using a different method to select based on the value now being alphanumeric? Do I need to manipulate the data in some way?
Code:
$sql = "SELECT * FROM checkedout";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userid = $row["userid"];
$barcode = $row["barcode"];
echo "$userid </br>";
echo "$barcode </br>";
$sql2 = "SELECT * FROM game WHERE barcode = " . $barcode . "";
$result2 = $conn->query($sql2);
while ($row2 = $result2->fetch_assoc()) {
$title = $row2["title"];
$console = $row2["console"];
echo "$title </br>";
echo "$console </br>";
}
checkedout table:
game table:

Insert is only doing the first row [duplicate]

This question already has answers here:
PHP Insert data from one table to another
(2 answers)
Closed 3 years ago.
I have a simple query that is returning some results from my database, it returns 4 rows, but when I do the insert it's only doing the first row and then stopping, does not seem to be doing an insert for each row that is returned from the first query.
$sql = "SELECT t.ID AS 'TopicID', t.seminar_id AS 'SeminarID', rl.resourceid AS 'ResourceID', r.ResourceType AS 'ResourceType'
FROM topic t
LEFT JOIN resourcelink rl ON rl.entityid = t.ID
LEFT JOIN resources r ON r.ResourceID = rl.resourceid
WHERE t.seminar_id = '124840'";
$result = mysql_query($sql);
// echo "<pre>";
// print_r($sql);
// echo "</pre>";
while($row = mysql_fetch_assoc($result))
{
$resourceID = $row['ResourceID'];
$resourceType = $row['ResourceType'];
if ($resourceID != '' && $resourceType != 1)
{
$sql_insert = "INSERT INTO resourcelink (resourceid, entityid, entitytype, linkorder, viewinplayer)
VALUES ($resourceID, $topicID, 1, 0, 0)";
$result = mysql_query($sql_insert);
}
}
The reason is that you're overwriting the $result variable when you do the first insert. So when the next iteration of the while loop calls mysql_fetch_assoc($result), it's fetching the result of the INSERT, not the result of the SELECT.
Since you never do anything with the result of the INSERT, there's no need to assign a variable. If you do need to use the result, you should use a different variable name. So change:
$result = mysql_query($sql_insert);
to
mysql_query($sql_insert) or die("Insert error: " . mysql_error());

how to get column values randomly in mysql [duplicate]

This question already has answers here:
MySQL select 10 random rows from 600K rows fast
(28 answers)
Closed 4 years ago.
i have a table named quiz ,it have six columns like id,question,option1,option2,option3,answer.i want to loop through all the values by using the following query
$sql = "SELECT id, option1, option2,option3,answer,question FROM quiz";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - question: " . $row["question"]. " " .
$row["option1"]. "<br>";
}
How can i get random values from mysql table everytime i want only 4 values.I am new to development .
welcome to Stackoverflow!
Use this;
$sql = "SELECT id, option1, option2,option3,answer,question FROM quiz ORDER BY RAND() LIMIT 4";
This will get rows 100% randomly! But, it can get you duplicates..

Selecting and displaying data from the last 5 entries in a table

So, after searching for a while here in stack overflow, I found a way of doing it:`
$sql = "SELECT username FROM (SELECT * FROM users ORDER BY id DESC LIMIT 5) sub ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
echo $row[0];`
However when I echo the $row[0] to get the first entry it doesn't display anything. I have checked my connection to the database and used the query on the phpmyAdmin and it worked fine, not sure why isn't it displaying the data (There is also a user in the table with the ID 1).
mysqli_fetch_assoc returns an associative array, not a numbered array. So the index of each column in the result is the column name, $row['username'].
If you want all 5 usernames, you need to call it in a loop. Each call just returns one row of the results, not all of them at once.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . '<br>';
}
To get a numbered array you use mysqli_fetch_row(). You still need the loop to get all of them.
while ($row = mysqli_fetch_row($result)) {
echo $row[0] . '<br>';
}

PHP GET Rows based on URL ID [duplicate]

This question already has answers here:
How can I get an unknown username given an ID?
(2 answers)
Closed 12 months ago.
I have a search function on my site which displays results from a MySQL db. Each search result is linked to a dynamic php page with the URL, i.e. /details.php?id=123.
I need the details.php page to get the ID (e.g 123) from the URL and then fetch all rows from the database with this ID, storing them in a variable for use later. I then need to be able to echo the rows at various points throughout the page to populate the content.
The code I have so far is:
<?php
$db = mysql_connect("","","") or die("Database Error");
mysql_select_db("items",$db);
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
?>
I’m fairly new to PHP so not sure if the code above will get all rows based on the ID, and then how to echo the rows within divs on the page?
You can use mysql_fetch_array() OR mysql_fetch_assoc() function with while loop (if multiple rows there) OR without while loop if there is only one row.
$query = "SELECT * FROM `items- table` WHERE `id`='" . $id . "'";
$result = mysql_query($query);
while($fetch = mysql_fetch_array($result))
{
echo "<div>".$fetch['column_name']."</div>";
}
Almost correct. Just add something like this:
while ($row = mysql_fetch_assoc($result)) {
echo '<div>';
foreach ($row as $key => $val) {
echo $key.' = '.$value.'<br/>';
}
echo '</div>';
}

Categories