MySQL Prepared Statement, write multiple rows - php

So far I have used prepared statements to get ONE row from a database. But how do I write multiple rows onto the page. Looked online and people only seem to be showing how to get the one row.
if ($count_sets->num_rows > 0) {
$query = "SELECT id,jpg,udate,imageset FROM images WHERE dodelete = ? AND udate = ? AND imageset = ?";
if ($stmt = $mysqli->prepare($query)) {
//echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
$stmt->bind_param("isi",$deleted,$session_date,$imageset);
$stmt->execute();
$stmt->store_result();
//Get result
$stmt->bind_result($result_id,$result_jpg,$result_date,$result_imageset);
//Number of rows returned
$count_rows = $stmt->num_rows;
}
} else {
echo "No images to process, do an upload first!";
}
$folder = str_replace("/", "", $session_date);
if ($count_rows > 0) {
echo "hel<br />";
echo $result_jpg[0];
}

Found some example code:
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT * FROM mytable where userid=? AND category=? ORDER BY id DESC");
$stmt->bind_param('ii', intval($_GET['userid']), intval($_GET['category']));
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($column1, $column2, $column3);
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}
$stmt->close();
It's the following part I didn't know how to do.
while($stmt->fetch())
{
echo "col1=$column1, col2=$column2, col3=$column3 \n";
}

Related

How to only show ID's not already in another table

I am trying to display records from a categories table that don't exist in another table. This works to a certain extent whereby if there are 3 records in the sp_cats table, the display from $stmt2 will show all records except 1 where it should be all except 3. So, it isn't looping through for some reason.
$stmt = $link->prepare("SELECT `sp_cat_id` FROM `sp_cats` WHERE `sp_id` = ?");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()){
$spCats = $row['sp_cat_id'];
echo $spCats . "<br/>";
}
}
$stmt->close();
echo "<br>";
$stmt2 = $link->prepare("SELECT `cat_id`FROM `categories` WHERE `cat_id` != ?");
$stmt2->bind_param("i", $spCats);
$stmt2->execute();
$result2 = $stmt2->get_result();
$numRows2 = $result2->num_rows;
if($numRows2 > 0){
while($row2 = $result2->fetch_assoc()){
$cat_id = $row2['cat_id'];
echo $cat_id . "<br/>";
}
}
$stmt2->close();
See this while() loop here,
while($row = $result->fetch_assoc()){
$spCats = $row['sp_cat_id'];
...
}
The problem is, in each iteration of while() loop you're overwriting $spCats value. Besides, you don't have to use two different queries, you can do everything in just one query, like this:
$stmt = $link->prepare("SELECT `cat_id`FROM `categories` WHERE `cat_id` NOT IN (SELECT `sp_cat_id` FROM `sp_cats` WHERE `sp_id` = ?)");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0){
while($row = $result->fetch_assoc()){
$cat_id = $row['cat_id'];
echo $cat_id . "<br/>";
}
}
$stmt->close();

Select * from table not working SQL

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

Need help fetching an array from a prepared statment

I am new to using prepared statement with PHP. I am trying to get the value of "full_name"... So far I am stuck over here. Can anyone please help figure this out? Thanks!
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$row = $stmnt->fetch();
You need to use bind_result to bind variables to the columns you want. Then each time you call fetch(), those variables will be updated with the next row's values. fetch() with mysqli does not return you the row/result.
This means you cannot use SELECT *. You need to specify which fields you want.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT full_name FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$stmnt->bind_result($full_name);
$stmnt->fetch();
echo $full_name;
Or, if you have the mysqlnd driver installed, you can use get_result() to get a result set just like if you had ran a normal query, not a prepared statement.
if($db->connect_error){
echo "Connection Error";
}
$id = 834;
$stmnt = $db->prepare("SELECT * FROM checkout_page where id = ?");
$stmnt->bind_param("i", $id);
if (!$stmnt->execute()) {
echo "Execute failed: (" . $stmnt->errno . ") " . $stmnt->error;
}
$result = $stmnt->get_result();
$row = $result->fetch_assoc();
echo $row['full_name'];

Why am I receiving only the first value for each element of the array?

I am not able to figure out why all of my results are repetitions of the first values it returns.
This code returns the same ID and formatted date repeated over and over again; however, I was expecting it to read a value and then transform that value for each entry in the DB. Here is my code:
<?php
include('../includes/conn.inc.php');
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$stmt->bind_result($id, $endDate);
while($row = $stmt->fetch()) {
$dataRow[] = array('id'=>$id,'endDate'=> $endDate);
};
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($endDate));
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
In your foreach you are always using the last values that were set from the last $stmt->fetch()
Try:
foreach($dataRow as $i) {
$newEndDate = date('Y-m-d',strtotime($i['endDate']));
$id = $i['id'];
$sql = 'UPDATE TABLE SET startDate = ? WHERE id= ? ';
$stmt = $mysql->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('si',$newEndDate, $id);
$OK = $stmt->execute();
}
if ($OK) {
echo $id . " " . $newEndDate . "done <br/>";
} else {
echo $stmt->error;
}
$stmt->close();
};
use get_result();
$dataRow = array()
$stmt = $mysql->prepare("SELECT id, endDate FROM TABLE ORDER BY id");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_array()) {
$dataRow[$row['id']] = $row['endDate'];
}
and you don't populate your $endDate in the second loop
foreach($dataRow as $i => $endDate){
$newEndDate = date('Y-m-d',strtotime($endDate));
... // rest of your code

num_rows is 0 when it should be >0 for php mysqli code

My num_rows is coming back as 0, and I've tried calling it several ways, but I'm stuck. Here is my code:
$conn = new mysqli($dbserver, "dbuser", "dbpass", $dbname);
// get the data
$sql = 'SELECT AT.activityName, AT.createdOn
FROM userActivity UA, users U, activityType AT
WHERE U.userId = UA.userId
and AT.activityType = UA.activityType
and U.username = ?
order by AT.createdOn';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('s', $requestedUsername);
$stmt->bind_result($activityName, $createdOn);
$stmt->execute();
// display the data
$numrows = $stmt->num_rows;
$result=array("user activity report for: " . $requestedUsername . " with " . $numrows . " rows:");
$result[]="Created On --- Activity Name";
while ($stmt->fetch())
{
$msg = " " . $createdOn . " --- " . $activityName . " ";
$result[] = $msg;
}
$stmt->close();
There are multiple rows found, and the fetch loop process them just fine. Any suggestions on what will enable me to get the number of rows returned in the query?
Suggestions are much appreciated. Thanks in advance.
You need to call $stmt->store_result() first, just before $stmt->num_rows.
Try to add this before you call num_rows;.
$stmt->store_result();
$stmt->store_result();
$numrows = $stmt->num_rows;
Check this: http://php.net/manual/en/mysqli-result.num-rows.php and this
http://php.net/manual/en/mysqli-stmt.num-rows.php
I don't know if this will fix it, but you can't bind_results until after you execute the query, if I'm not mistaken.
Also your while loop:
while ($stmt->fetch())
{
$msg = " " . $createdOn . " --- " . $activityName . " ";
$result[] = $msg;
}
you will lose all of the $msg variables with each iteration of the loop, except the last setting because you either need to do $msg .= or make $msg an array $msg[] =

Categories