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

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

Related

How to use SQL LIKE clause with mysqli prepared statements [duplicate]

This question already has answers here:
How can I with mysqli make a query with LIKE and get all results?
(2 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
I'm attempting to use a SQL LIKE clause with mysqli prepared statements.
I have already tried other examples such as
$sysName = "{$_POST['ss']}%";
and
$sysName = $_POST['ss'] . '%';
if(isset($_POST['ss'])) {
$sysName = $_POST['ss'] . '%';
if(strlen($sysName) >0) {
$qry = mysqli_stmt_prepare($link, "SELECT * FROM tblSchools WHERE systemName LIKE ?");
mysqli_stmt_bind_param($qry,'s',$sysName);
mysqli_stmt_execute($qry);
$result = mysqli_stmt_get_result($qry);
}
}
If $_POST['ss'] is populated with the word sys and there exists a systemName in tblSchools called 'system' then the result set should include the row information that pertains to the 'system' row. No matter what I put in there though the result always comes back null. My connection to the database is successful. I have tested with mysqli_query and just straight strings successfully, but when I switched to prepared statements on the LIKE clause it doesn't work. I've been beating my head against this problem for almost a full day now.
EDIT: In response to first answer
Still doesn't work
$stmt = mysqli_stmt_init($link);
$sysName = "sys%";
if(strlen($sysName) >0) {
if(!mysqli_stmt_prepare($stmt, "SELECT * FROM tblSchools WHERE systemName LIKE ?")) {
echo "1";
exit;
} else {
if(mysqli_stmt_bind_param($stmt,'s',$sysName)) echo "2";
if(mysqli_stmt_execute($stmt)) echo "3";
$result = mysqli_stmt_fetch($stmt);
$row = mysqli_fetch_array($result);
var_dump($row);
echo "Hey";
}
}
Prints 2 and 3 not 1
Try this:
$link = \mysqli_connect("127.0.0.1", "user", "password", "dbname");
if (!$link) {
$error = \mysqli_connect_error();
$errno = \mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
$query = "SELECT * FROM tblSchools WHERE systemName LIKE ?";
$stmt = \mysqli_stmt_init($link);
if (!\mysqli_stmt_prepare($stmt, $query)) {
print "Failed to prepare statement\n";
exit;
} else {
$sysName = 'sys%';
\mysqli_stmt_bind_param($stmt, "s", $sysName);
\mysqli_stmt_execute($stmt);
$result = \mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result);
var_dump($row);
}
it works for me

How to Query in PHP/ MySQL when there is a period (.) in String

How do I query from a MySQL database when I have a period (.) in string using PHP.
$variable = "my.email#email.com";
$variable = mysqli_real_escape_string($conn, $variable);
$query = "Select * from table WHERE email = '$variable' ";
Apparently this works when I ran it in PhpMyAdmin SQl tab. But when I run it In my code it does not work. Other strings that don't have a period using the same code are working perfectly. What could be the issue
for those who are asking for my original code here it is
//I get the emails from the url
$notit = mysqli_real_escape_string($conn, $_GET['username']);
//I pass my variable in the query
$sql = "SELECT * ";
$sql.=" FROM ordrs ";
$sql.=" WHERE client_email = '$notit' ";
$query=mysqli_query($conn, $sql) or die("try again");
Try this code it works for me try using PDO.
try{
$pdo = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_username, $db_password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$email = "code.sample#mail.co.ke";
$stmt = $pdo->prepare('SELECT email FROM user WHERE email = ?');
$stmt->bindParam(1, $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Sample output by eg: echo '<h2>'. $user['email'] . '</h2>';
You should use prepared statements. Otherwise, possible of sql injection vulnerability.
Example:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("Select * from table WHERE email = ?");
$stmt->bind_param("s", $email);
// set parameters and execute
$email = "john.doe#example.com";
$stmt->execute();
I figured where the issue was the query was fine the error was coming from json_encode which I din't expect . I hope this question helps others in the future who are facing the problem questioned. Thanks for the help
thanks for the help. Cheers

PHP prepared statement not working [duplicate]

This question already has answers here:
How do I escape reserved words used as column names? MySQL/Create Table
(4 answers)
Closed 2 years ago.
I am making a prepared statement in PHP and my code is fine until I add in 'id' and 'key' to my parameters. They are definitely in the table that I am requesting too. What is wrong? Thanks in advance!
ERROR: Call to a member function bind_param() on boolean
if($_POST['userx']){
echo '<div id="div2"><div id="font2">Dashboard</div>';
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
$stmt->close();
Key is a reserved keyword in mysql.
It's a good habit to enclose field names and table names in backticks in queries but also to check for errors.
$queryA = "SELECT `name`,`profo`,`password`,`id`,`key` FROM `collegestudents` WHERE `email` = ?";
$stmt = $connection->prepare($queryA);
if ($stmt) {
$stmt->bind_param('s',$_POST['userx']);
...
}
else {
echo "MySQL ERROR: " . $connection->error;
}
$stmt = $connection->prepare($queryA);
returns boolean(false)
make sure your query is correct
you can do a simple check like this
$stmt = $connection->prepare($queryA);
if (!$stmt) {
echo "failed to run";
} else {
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
$stmt->fetch();
}
Edit:
if you are using PDO you were doing it wrong it should be like this
$stmt = $conn->prepare("SELECT name,profo,password,id,key FROM
collegestudents WHERE email = :email");
$stmt->bindParam(':email', $email);
Change your database connection file with
<?php $con = new PDO('mysql:host=127.0.0.1;dbname=yourdatabasename;','username',''); ?>
Then change below line
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = ?";
$stmt = $connection->prepare($queryA);
$stmt->bind_param('s',$_POST['userx']);
$stmt->bind_result($name1,$profo,$password1,$key,$id);
$stmt->execute();
with
$queryA = "SELECT name,profo,password,id,key FROM collegestudents WHERE email = :v";
$stmt = $connection->prepare($queryA);
$stmt->execute( array('v' => $_POST['userx']) );

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