how to make mysqli prepared statement and fetch result? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I can't understand how to create a prepared statement, and all tutorials I have seen was fetching only column.
My normal sql query
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM files WHERE id=$id ") or die(mysql_error());
$row = mysql_fetch_array($result);
$name = $row['name'];
$date = $row['date'];
Please show me how to create a prepared statement and how to fetch more than one column and insert the date into variables.

First of all it's not a good idea to use SELECT * in production. Instead specify needed columns explicitly. Take a look at https://stackoverflow.com/a/65532/1920232.
Now your code might look like
$id = $_GET['id'];
$db = new mysqli('localhost', 'user', 'password', 'dbname');
$sql = 'SELECT name, date FROM files WHERE id = ?'; //specify columns explicitly
if ($stmt = $db->prepare($sql)) { //create a prepared statement
$stmt->bind_param('i', $id); //bind parameters
$stmt->execute(); //execute query
$stmt->bind_result($name, $date); //bind result variables
$stmt->fetch(); //fetch values
}
$db->close();
echo $id, ' ', $name, ' ', $date;
Note: All error handling intentionally skipped for brevity.

Related

How to assign a DB value to a PHP variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to assign a DB value to a PHP variable. The database is SQL. I want the database value to be $HaveOfficialPage. How can I do this?
$connection = mysqli_connect('localhost', '', '', '');
if($connection){
echo "Connected";
}
else {
die("Database connection failed");
}
$query = "SELECT HaveOfficialPage FROM vf_Category";
$result = mysqli_query($connection, $query);
if(!$result){
die("Query failed" . mysqli_error());
}
If you’re trying to iterate through the results:
while ($row = mysqli_fetch_row($result)) {
$haveOfficialPage = $row[0];
// do something with the variable
}
If you’re getting only one record:
$row = mysqli_fetch_assoc($result);
$haveOfficialPage = $row["HaveOfficialPage"];
To select a category with a condition, use prepared statements
$paths = explode("/",$_SERVER["REQUEST_URI"]);
$category = end($paths);
$query = "SELECT HaveOfficialPage FROM vf_Category WHERE category_name = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $category);
mysqli_stmt_bind_result($stmt, $haveOfficialPage); // here we assign the result to your variable
mysqli_stmt_fetch($stmt); // fetch
echo $haveOfficialPage;

Turning a HTML form input into an PDO variable [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want the user to specifiy a number, this number will be used in my SQL statement when connecting to the database. If the user inputs five I want the five first rows in the table to be displayed.
If i write "SELECT * FROM TABLE WHERE ID <= 5" it works, but my variable is being fetched from a form. When I use $variable = $_POST['variable'] and print it out using "SELECT * FROM TABLE WHERE ID <= $variable" no results are being returned. Why is that?
you need to bind that variable if you use PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT * FROM TABLE WHERE ID <= :id");
// bind params
$stmt->bindParam(":id", $_POST['variable']);
$stmt->execute();
// fetch with
// $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "OK";
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
According to http://www.w3schools.com/php/php_mysql_prepared_statements.asp
Looked through the code once again, just a simple typo:
Works with:
$sql = 'SELECT * FROM sql WHERE id <= ' . $items;
Before this I had
$sql = 'SELECT * FROM sql WHERE id <= $items';

php decode special entities in mysql [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am very new to PDO and I am trying to decode all the rows in my table "test" which contains special entities for instance "('L& eacute;on: The Professional')" instead of "Léon:The Professional".
So, here is what I tried:
<?php
require_once('connection.php');
$stmt = $conn->prepare("SELECT * from test");
$stmt->execute();
while ($results = $stmt->fetch()){
$b = html_entity_decode($stmt);
echo $b;
}
but I have no output printed..
Could someone kindly help me fix it?
prepare() returns a statement object ($stmt in your case)
fetch() returns associative array where the index would be the column name
$sql = "SELECT column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = array()
while ($row = $stmt->fetch()){
$resutlt[] = array('column1' => html_entity_decode($row['column1']),
'column2' => html_entity_decode($row['column2']),
'column3' => html_entity_decode($row['column3'])
);
}
var_dump($result);
return $result;
EDIT: to replace the values
//prepare select
$sql = "SELECT id, column1, column2, column3 from test";
$stmt = $conn->prepare($sql);
$stmt->execute();
//prepare update
$update_sql = "UPDATE test SET column1=?,column2=?,column3=? WHERE id = ?;";
$update_stmt = $conn->prepare($update_sql);
while ($row = $stmt->fetch()){
//update
$update_stmt->execute(array(html_entity_decode($row['column1']),
html_entity_decode($row['column2']),
html_entity_decode($row['column3']),
$row['id']
);
}
You did not define $query, thus it has no execute() function. If you wish to execute your prepared statement, you should call $stmt->execute().

How do I create a prepared statement? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I cannot find any documentation that adequately explains how to use them. How to you retrieve variables from a query and use them and what do the parameters mean to the queries? I want to make my website safe from sql injection and I don't have a clue how to get the following code optimized for safety. I understand how sql injection works, I just don't know how to create the prepared statements or retrieve queries.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$tempProf = $_POST["professor"];
$tempProfArray = explode("=",$tempProf);
$prof = $tempProfArray[1];
$tempName = $_POST["name"];
$tempNameArray = explode("=",$tempName);
$name = $tempNameArray[1];
$tempNum = $_POST["number"];
$tempNumArray = explode("=",$tempNum);
$num = $tempNumArray[1];
$tempSec = $_POST["section"];
$tempSecArray = explode("=",$tempSec);
$section = $tempSecArray[1];
$tempCat = $_POST["category"];
$tempCatArray = explode("=",$tempCat);
$category = $tempCatArray[1];
$con=mysqli_connect("localhost","root","*******","******");
$result = mysqli_query($con,"SELECT * FROM professors where id='$prof'");
$row = mysqli_fetch_array($result);
if(empty($prof) || empty($name) || empty($num) || empty($section) || empty($category))
{
echo "emptyField";
}
elseif(!is_numeric($num) || !is_numeric($section))
{
echo "NaN";
}
elseif(empty($row))
{
mysqli_query($con,"INSERT INTO classes (className, classNumber, section, classCategory)
VALUES ('$name','$num','$section','$category')");
$classTemp = mysqli_query($con,"SELECT id FROM classes where className='$name' and classNumber='$num' and section ='$section'");
$classTempArray = mysqli_fetch_array($classTemp);
$classId = $classTempArray['id'];
mysqli_query($con,"INSERT INTO professors (name, classes) VALUES ('$prof','$classId')");
$profTemp = mysqli_query($con,"SELECT id FROM professors where name='$prof'");
$profTempArray = mysqli_fetch_array($profTemp);
$profId = $profTempArray['id'];
mysqli_query($con,"UPDATE classes SET professor = '$profId' WHERE id = '$classId'");
echo "success";
}
else
{
$profName = $row['id'];
mysqli_query($con,"INSERT INTO classes (professor, className, classNumber, section, classCategory)
VALUES ('$prof', '$name','$num','$section','$category')");
echo "success";
}
?>
In general, something like this will suffice (note that I use the object orientated way of accessing connections, not procedural like you)
$stmt = $con->prepare( 'INSERT INTO classes (professor, className, classNumber, section, classCategory) VALUES (?, ?, ?, ?, ?)' )
$stmt->bind_param( 'ssiss', $prof, $name, $num, $section, $category );
$stmt->execute();
In this case I am assuming that everything but $num is a string, and $num is an integer.
Here is the relevant doc for binding params: http://www.php.net/manual/en/mysqli-stmt.bind-param.php
$sql="SELECT id FROM classes WEHERE className=? AND classNumber=? AND section =?";
$stmt =$con->prepare($sql);
$stmt->execute(array($name,$num,$ection));
//you can apply this for other queries

How to use PDO Statement to Bind a for loop index? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have two MySQL query statements that’s need to be convered to PDO using prepare and
BindParam. Any help is appreciated. Thanks.
Here is the problem:
The two non PDO statements are in a for loop and are setup like this:
for ($i = 0; $i < $numItem; $i++)
{
// some codes…, then
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = ".$productId[$i]."";
$result = dbQuery($sql);
// Some more codes goes here, then.....the 2nd query
$sql = "UPDATE ct_car
SET ct_qty = $newQty
WHERE ct_id = {$carId[$i]}";
dbQuery($sql);
// Some more code, some more codes goes here
// end the for loop
Now, for the new PDO statements, I would like to do something like this to replace the two statements in the for loop above:
// check stock
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = :productId[$i]";
try
{
// Build the database statement
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":productId[$i]", $productId[$i], PDO::PARAM_INT);//not sure here
$stmt->execute();
// more code here....
// more codes...
// then the next sql pdo statement:
// update
$sql = "UPDATE ct_car
SET ct_qty = :newQty
WHERE ct_id = {$carId[$i]}";
try
{
// Build the database statement
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":newQty", $newQty, PDO::PARAM_INT);
$stmt->bindParam(":cartId[$i]", $cartId[$i], PDO::PARAM_INT); // not sure here
$stmt->execute();
$count = $stmt->rowCount();
//more codes....
// code continues....
//end for
Have a look at http://php.net/manual/de/pdostatement.bindparam.php.
The placeholder needs to be a string or a ? sign. (But you cannot mix named placeholders with ? placeholders)
$sql = "SELECT pd_name, pd_qty, pd_type
FROM ct_products
WHERE pd_id = :productId";
$stmt->bindParam(":productId", $productId[$i], PDO::PARAM_INT);
// update
$sql = "UPDATE ct_car
SET ct_qty = :newQty
WHERE ct_id = :cartId";
$stmt->bindParam(":newQty", $newQty, PDO::PARAM_INT);
$stmt->bindParam(":cartId", $cartId[$i], PDO::PARAM_INT);
PDO::PARAM_INT is right if it's really an integer value. The default if you don't set it is PDO::PARAM_STR.
Another thing: you could get into troubles with bindParam because the variable is bound as a reference. In your case it should not matter because you're running execute immediate after the binding. Else have a look at bindValue which you can use in the same way.

Categories