PHP Multiple Prepared Statements - php

I would like to execute two statements and print the results within a while loop. Each statement will select data from two different tables.
I'm not sure the best way to approach this.
My code so far is as follows;
$conn = new mysqli('localhost', 'user', 'password', 'db');
if ($conn->connect_errno > 0) {
die('Unable to connect to database [' . $conn->connect_error . ']');
}
$curDate = date("Y-m-d");
//first stmt
$stmt = $conn->prepare("SELECT start, status FROM log WHERE start >= ?");
$stmt->bind_param('s', $curDate);
$stmt->execute();
$stmt->bind_result($start, $status);
$stmt->close();
//second stmt
$stmt = $conn->prepare("SELECT time FROM params");
$stmt->bind_result($time);
$stmt->execute();
$stmt->close();
/* fetch values and echo for testing */
while ($stmt->fetch()) {
echo $start;
echo $status;
echo $time;
}
Any help is appreciated.

In general, there is nothing special in running two or dozen prepared statements - you just have run them one by one. Thus there is no "best way" at all.
In your particular case the best way is to get rid of prepared statements:
$time = $conn->query("SELECT time FROM params")->fetch_object()->time;
$res = $conn->query("SELECT start, status FROM log WHERE start >= CURDATE()");
while($row = $res->fetch_object())
{
echo $row->start;
echo $row->status;
echo $time;
}

Related

PHP echo total number of rows from SQL query

I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!
$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);
echo $count;
You should use php prepare statement like this
$count = 0;
$mysqli = new mysqli(host, dbUser, dbPassword, dbName);
mysqli_set_charset($mysqli, "utf8");
$sql = "select count(*) from advisors";
if ($stmt = mysqli_prepare($mysqli, $sql))
{
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $c);
if (mysqli_stmt_fetch($stmt))
{
$count = $c;
}
mysqli_stmt_close($stmt);
}
return $count;
For more information, here is the link for php prepare statement
Documentation of php prepare statement
You should use COUNT in query and see if it works,
"SELECT COUNT (number) as number FROM advisors";
By the way, I noticed a typo in $count, it should be $count = mysqli_num_count($result).

Using prepared MySQLi statements to produce associative array

I've read a few related questions to this, but in each case I've been unable to get their code to work in my context.
Following some injection attempts, I am trying to implement prepared statements into my site, while changing as little code as possible. Importantly, I want the responses to my SELECT queries to by outputted as associative arrays: e.g. $row['name'].
Here is an example of code that I have right now (without preprepared statements):
// Create connection
$db = new mysqli('localhost', 'username', 'password', 'seatingplan');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Get class name
$sql = <<<SQL
SELECT *
FROM `class`
WHERE `userid` = '$userid'
AND `classid` = '$classid'
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$classname = $row['classname'] ;
}
Is there a straightforward way of adapting this for prepared statements? Based on other questions, this is as far as I've got (but it doesn't work - it only returns 1 for each row, rather than the actual variable):
$stmt = $db->prepare("SELECT *
FROM `class`
WHERE `userid` = ?
AND `classid` = ?");
$stmt->bind_param("ss", $userid, $classid);
$result = $stmt->execute();
$stmt->store_result();
while($data = $stmt->fetch()){
echo $data ;
}
Just define the array and use it for example in your code:
$stmt = $db->prepare("SELECT *
FROM `class`
WHERE `userid` = ?
AND `classid` = ?");
$stmt->bind_param("ss", $userid, $classid);
$stmt->execute();
$result=$stmt->get_result();
$row= array();
$i=0;
while ($data = $result->fetch_assoc())
{
$row[$i]['name']=$data['name'];
$i++;
}
echo $row;

How would I turn this into a prepared statement? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I'm new to prepared statements so I apologise in advance if this is a basic question but how would I turn the following code into a prepared statement and execute it later on?
<?php
$myQuery = "SELECT * FROM test WHERE ID=" . $_GET['ID'];
//run query
$result = $con->query($myQuery);
if (!$result) die('Query error: ' . mysqli_error($con));
?>
Take a look to http://www.w3schools.com/php/php_mysql_prepared_statements.asp, http://php.net/manual/en/mysqli.quickstart.prepared-statements.php (mysqli lib), or http://php.net/manual/en/pdo.prepared-statements.php (PDO lib).
Ex:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare statement
$stmt = $conn->prepare("SELECT * FROM test WHERE ID=?");
// set parameters
$stmt->bind_param("i", $_GET['ID']);
// execute
$stmt->execute();
// close resources
$stmt->close();
$conn->close();
To do the call you could use somethign like;
$sCompanyCode = 'fkjahj12321';
$con = new PDO("connection string");
$sql = "SELECT CompanyID From Companies WHERE CompanyCode = :CompanyCode";
$st = $con->query( $sql );
$st->bindValue(":CompanyCode", $sCompanyCode, PDO::PARAM_STR);
$st->execute();
To retrieve 1st or singular result;
if($row = $st->fetch()){
return (int)$row[0];
}
For multiple results;
$aResults = array();
while ($row = $st->fetch()){
$aResults[] = $row;
}

PHP prepare and execute

I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.

PDO prepared statements in functions [duplicate]

This question already has answers here:
How do I loop through a MySQL query via PDO in PHP?
(3 answers)
Closed 9 years ago.
I am currently using MySQL with PHP but am looking to start MySQLi or PDO
I have while loops like:
$sql="select from ... ";
$rs=mysql_query($sql);
while($result=mysql_fetch_array($rs))
{
$sql2="select from table2 where id = $result["tbl1_id"] ";
}
If I put my MySQLi or PDO queries into a function how can I run things like the above? Doing while loops with queries inside the while loops?
Or is if easier to not do the functions at all and just run the prepared statements as normal?
You wouldn't. And to be honest.. Even in the old days you would not do it this way, but like this:
$sql="select from ... ";
$rs=mysql_query($sql);
$ids = array()
while($result=mysql_fetch_array($rs))
{
$ids[] = $result["tbl1_id"];
}
$sql2="select from table2 where id in ".implode(',', $ids) .";
Or even better, you use a join to run the query just once, on all the tables that need to provide info.
In PDO you can do the same thing. Get all the ID's and the execute a query
I usually take the approach of preparing the query and not using a function. Also I am not clear as to what exactly it is that you want. You want to make your queries as quick and efficient as possible so you should not look to run a while look within another while loop.
This is how my PDO queries usually look
My connection:
$host = "localhost";
$db_name = "assignment";
$username = "root";
$password = "";
try {
$connection = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}
MY query:
$query = "SELECT * FROM Table";
$stmt = $connection->prepare( $query );
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
}
It's a duplication question like oGeez say, you have to learn how to code PDO in PHP and other before asking question,
this is the answer:
$dbh = new PDO("mysql:host=" . HOST . ";dbname=" . BASE, USER, PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = 'SELECT * FROM table';
$stmt = $dbh->query($query);
$items = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach($items as $item {
print_r($item);
}
the main reason to put it in a function would be if you use the query in multiple files. i have a web app with many queries and i like to keep them in a separate file so that they're easier to track down if i need to make changes. the main thing is that you 1) have to pass your database as a parameter and 2) return the results
function pdoquery($db, $parameter){
$query = "SELECT * FROM table WHERE column=?";
$stmt = $db->prepare($query);
$stmt->bindValue(1, $parameter, PDO::PARAM_STR); //or PARAM_INT
if (!$stmt->execute()) {
echo "Could not get results: (" . $stmt->errorCode . ") " . $stmt->errorInfo;
exit;
}
else
$result = $stmt->fetch();
$db = null;
return $result;
}
but as others have mentioned, if its only used once, there's no need for a function, and looping through the results is best done outside of the function as well. however, it is possible to do it inside the function if you want to.

Categories