php mysqli prepared statement all ways skipping the first result - php

I have a class which takes data from the database. Everything works but the results 'clips' the first result.
For example I have 15 items in my database so by echoing out the id I should get
1
2
3
4
...
13
14
15
But I get
2
3
4
...
13 14 15
The statement is working as the data is displaying but why is it all ways missing the first result.
CODE:
private function formatResults($data){
while($row = $data->fetch(\PDO::FETCH_ASSOC)){
echo $row['product_id'].'<br/>';
}
}
public function getAllProducts(){
if($this->databaseConnection()){
$stmt = $this->db_connection->prepare("SELECT * FROM products ORDER BY product_id DESC");
$stmt->execute();
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
$this->formatResults($stmt);
}
}
That is the original function which works, (except missing out the first row).
I also tried just targeting one row to see if it made a difference but no nothing gets returned.
public function getAllProducts(){
if($this->databaseConnection()){
$stmt = $this->db_connection->prepare("SELECT * FROM products WHERE product_id = ? ORDER BY product_id ASC");
$a =1;
$stmt->bindParam(1,$a,\PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
echo $row['product_id'].'<br/>';
}
}
}
Im not sure what to do here, the function appears to work.

Because you're fetching/throwing away a row:
$result = $stmt->fetch(\PDO::FETCH_ASSOC); // fetch first row
$this->formatResults($stmt); // fetch all the other rows
Simply eliminate that "fetch first row" line.

Related

looping through rows of a mysql table with non sequential index

I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}

Best way to identify a mysql changed "group by" field value in a statement fetch in php?

I have a sql query in my php:
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
Now, I have to echo back several HTML tables based on different orderIds, so basically if the orderId is changed, a new HTML table will be created and contains the info of all the things under this orderId. This is what I have done(kinda pseudocode, please ignore the syntax error. My real code is far more complicated but the idea is here: set an oldOrderId and check it with the newly fetched orderId and see if the orderId is changed):
$sql = "SELECT * FROM orderTaken WHERE orderStatus='10' GROUP BY orderId ORDER BY orderTakenTime DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$count = $stmt->rowCount();
for ($i = 0; $i<$count + 1; $i++ ){
if ($row = $stmt->fetch()){
$orderId = $row["orderId"];
$2ndField = $row["2ndField"];
$3rdField = $row["3rdField"];
...
// check if $oldOrderId is set
if (isset($oldOrderId)){
// and compare, if the orderId changes, end the table and create a new one
if ($oldOrderId != $orderId){
echo "</table><br>";
echo "<table><tr><th>...</th></tr>";
...
//UPDATE old orderId
$oldOrderId = $orderId;
// if orderId doesn't change, continue echo table content
} else {
echo "<table><tr><td>...</td></tr>";
}
// if the oldOrderId is not set, it means this is the first fetched row, and the very first table will be created
} else {
echo "<table><tr><th>...</th></tr>";
...
echo "<table><tr><td>...</td></tr>";
...
//SET oldOrderId
$oldOrderId = $orderId;
}
}
if ($i == $count) {
//End the last table
echo "</table><br>";
}
}
The code can run but will be buggy sometimes and I don't think this is a smart way to identify it. Is there any existed method like
$row = $stmt->fetch().prev()
to get the last row's orderId's value? Or if there's any better way to perform it?
Thanks!
The problem is your inclusion of GROUP BY orderId in your query. What this does is give you one row per each orderId in your table.
Since you are using SELECT *, then all you are getting back is one row for each orderId and one of the other values in the table for each of the other fields.
When using GROUP BY, you usually want to add a "group function" - like SUM(), COUNT(), GROUP_CONCAT(), etc. - to your query.
Your approach with the $oldOrderId is fine and could work if you change your query to something like:
SELECT * FROM orderTaken
WHERE orderStatus='10'
ORDER BY orderID DESC, orderTakenTime DESC

Can I repeat fetchColumn in a function?

I'm trying to show 3 different values in 3 different column in a table. My first $results is okay, it's shows what it has to shows in my database but the second and the third doesn't show up. So tell me guys, how can I fix that problem? How can I show my 3e column and the other one?
public function Show($name) {
$st = $this->db->prepare("SELECT * FROM form WHERE username='$name'");
$st->execute();
$results = $st->fetchColumn(2);
print("Votre adresse: $results <br>");
$results = $st->fetchColumn(3);
print("Votre met: $results <br>");
$results = $st->fetchColumn(4);
print("Votre age: $results <br>");
}
we cannot use fetchColumn and fetchAll multiple times..so that's why we store it in a variable and then fetch data with the help of foreach loop statement for echo all data..but try this one code may be it will be helpful for you
function fetch_det()
{
$query=self::$db->prepare("select * from clas_products");
$query->execute();
$dta=$query->fetchAll(PDO::FETCH_COLUMN,0); //you can enter column num 2,3,4 instead of 0
print_r($dta);
}

Get value of the last record in a record set when using MySql and PHP

When selecting an displaying data using PHP and MySql, how can I get value of the last row in a record set? Is there a built in function in MySql or Php to do this?
For Eg (using PDO):
select id from table limit 5;
Output:
1
2
3
4
5 -> How can I get this value to pass to a function, all things being the same
while( $row = $stmt->fetch() ) {
echo $row['id'];
}
// The value of id of the last row i.e 5 needs to go into a function
functionName(id value of last row goes here)
How can this be done?
$last_id = 0
while( $row = $stmt->fetch() ) {
echo $row['id'];
$last_id = $row['id'];
}
functionName($last_id)
You can use PHP's end($array) to get the last item in the array
Try MAX()
SELECT max(id) FROM table
Try this...
select id from table ORDER BY id DESC limit 5;
This way you will get last 5 records.
I am not that good in PHP but, still...
I think fetch(PDO::FETCH_ORI_LAST) best suits your requirement.
Example:
$stmt = $conn->query("SELECT firstnme, lastname FROM employee");
$row = $stmt->fetch(PDO::FETCH_ORI_LAST);
print "Name: <p>{$row[0] $row[1]}</p>";
Refer to:
Fetching rows from result sets in PHP (PDO)
you can order your select descending and limit 1
select id
from table
order by id DESC
limit 1
if you want all rows, and just get the last in php, then as #Shamil said, end() works well

What does this SQL statement do?

I am trying to understand this SQL statements :
$id = 5;
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
Can someone please explain me step by step what exactly is going on here?
From what i understand :
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
1) $stmt is about to take as iinput an SQL query. The SQL query is to select all the rows from a table that their id is equal to 5.
$stmt->execute(array('id' => $id));
2) We execute the statement. Now the $stmt has these rows?
$row = $stmt->fetch()
3) This is the most confusing line for me. What exactly happens here? Variable "row" takes one by one the rows that have id = 5 ? Is that what fetch() does ? And if yes , how exaxtly does it return the results? Its an array of all the correct answers? EG all the rows that have id = 5 ? I dont understand how exactly this while loop works here.The first time it runs "row" will have the first row ? The second time it runs , will have the second row that satisfies our creteria (id = 5) and so on? Is it like that every time i run fetch one result will be returned? And next time i run fetch , the next result , till there is no more result to satisfy the query?
I thing i am so close to get this one. Anything that could help me understand it completely would be highly appreciated !
I'll explain as comments:
$id = 5;
// Create a prepared statement - don't actually execute the statement yet.
// The :id value in the statement will be replaced by a parameter value (safely) when the
// statement is executed
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
// Execute the statement against the DB - the $stmt var now contains the result set for the
// executed statement. e.g. it contains *all* the results that the query fetched
$stmt->execute(array('id' => $id));
// Now we loop through the rows in the result set (they are all in memory at this point).
// "fetch" will start from row 1 and return the next result each time you call it again.
// when there are no more rows it returns FALSE and therefore breaks out of the while loop
while($row = $stmt->fetch()) {
print_r($row);
}
Just checking docs also and whilst this is how it was done previously (been years since I've touched PHP) it looks like stmt->fetch() actually places results into bound variables:
http://php.net/manual/en/mysqli-stmt.fetch.php
$row = array();
stmt_bind_assoc($stmt, $row);
// loop through all result rows
while ($stmt->fetch())
{
print_r($row);
}
Does the code you originally posted actually work? It doesn't appear you bind any variables and therefore since the $stmt-fetch() call returns bool TRUE/FALSE it would seem to be that $row would not get set to anything but TRUE/FALSE
here it uses PDO for execution,
Repeated SELECT using prepared statements through which you can call repeated query
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
it defines the prepared statement where :id is placeholder
$stmt->execute(array('id' => $id));
this places assigns the value to placeholder and execute the query
$row = $stmt->fetch()
it fetch the record from select
for more reference visit the link
http://www.php.net/manual/en/pdo.prepared-statements.php

Categories