How do I go through the result of a parameterized query? - php

I'm trying to go through the result of a paremeterized query in PHP.
I'm trying this way
//creating a prepared statement
$stmt = $mysqli->stmt_init();
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0;
while($stmt->fetch())
{
if ($i++%2 == 0) $trow = "even"; else $trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$row['pcode']}</td><td>{$row['price']}</td><td>{$row['description']}</td>";
echo " </tr>";
}
if ($i==0) {
echo "<tr class='even'><td colspan='3'><h3>No Results.</h3></td></tr>";
}
But my code is entering the if statement.
How can I go through the result?
The database is MySQL.
<?php
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname) or die('Did you setup/reset the DB? <p><b>SQL Error:</b>' . mysql_error($conn) . '<p><b>SQL Statement:</b>' . $query);
function execute_query($the_query){
global $conn;
$result = mysql_query($the_query) or die('<font size=2><b>SQL Error:</b>' . mysql_error($conn) . '<br/><p><b>SQL Statement:</b>' . $the_query . '<br/>Did you run <i>setupreset.php</i> to setup/reset the DB?</font>');
return $result;
}
?>

You need to bind the result to some variables:
$query = "SELECT pcode,price,description FROM products WHERE description like ? ORDER BY PRICE";
$stmt = $mysqli->prepare($query);
$search_criteria = '%'.$search_criteria.'%';
$stmt->bind_param('s', $search_criteria);
$stmt->execute();
$i=0; $pcode; $price; $description;
$stmt->bind_result($pcode, $price, $description);
while($stmt->fetch()) {
if ($i++%2 == 0)
$trow = "even";
else
$trow = "odd";
echo " <tr class='{$trow}'>";
echo " <td>{$pcode}</td><td>{$price}</td><td>{$description}</td>";
echo " </tr>";
}

Related

PHP Fetch row data from Mysql via ID

I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer

Fatal error: Uncaught Error: Call to undefined function mysqli_stmt_get_result()

I'm dealing with a fatal error, and I see a lot of solutions for it everywhere but I can't seem to find the right solution that fits in my code...
so this is the code where it goes wrong:
$link = mysqli_connect($server, $gebruiker, $wachtwoord, $database);
if($link === false) {
die("ERROR: Kon geen verbinding maken. " . mysqli_connect_error());
}
if(isset($_REQUEST['term'])) {
$sql = "SELECT * FROM producten WHERE naam LIKE ?";
if($stmt = mysqli_prepare($link, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $param_term);
$param_term = '%' . $_REQUEST['term'] . '%';
if(mysqli_stmt_execute($stmt)) {
$result = mysqli_stmt_get_result($stmt);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<p>" . $row["naam"] . "</p>";
}
} else {
echo "<p>Geen producten gevonden</p>";
}
} else {
echo "ERROR: Kon $sql niet uitvoeren. " . mysqli_error($link);
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
this is the part that messes it all up:
$result = mysqli_stmt_get_result($stmt);
Who can help me in the right direction, thanks!
I fixed it, the solution:
if(isset($_REQUEST['term'])) {
$conn = mysqli_connect($server, $gebruiker, $wachtwoord, $database); //Connection to my database
$query = "SELECT id, naam FROM producten WHERE naam LIKE ?";
$statement = $conn->prepare($query);
$term = "%".$_REQUEST['term']."%";
$statement->bind_param("s", $term);
$statement->execute();
$statement->store_result();
if($statement->num_rows() == 0) {
echo "<p>Geen producten gevonden ".$_REQUEST['term']."</p>";
$statement->close();
$conn->close();
} else {
$statement->bind_result($id,$naam);
while ($statement->fetch()) {
echo "<p>" . $naam . "</p>";
};
$statement->close();
$conn->close();
};};

Is it possible to assign sql table value to a variable in php?

Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();

MySQL Prepared Statement, write multiple rows

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";
}

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

Categories