Convert to mysqli Prepared Statements from Procedural ones - php

I need help with the follow code to change it from Procedural to Prepared Statement. I will do my best to code it:
Default procedural script MYSQLI default
<?php
$conn = mysqli_connect ('localhost', 'gggggg', 'gggggg') ;
mysqli_select_db ($conn, 'ggggg');
$anti_injection = mysqli_real_escape_string($_GET['user']);
$sql = "SELECT * FROM profiles WHERE username =".$anti_injection);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($sql)) {
$username = stripslashes($row['username']);
$age = stripslashes($row['age']);
$gender = stripslashes($row['gender']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
CATEGORY <?php echo $username; ?>
TITEL <?php echo $age; ?>
CONTENT <?php echo $sex; ?>
</body>
</html>
<?php
}
?>
#
NOW MY CHANGES TO STATEMENTS HOPE IT WORKS
#
$query = $sql->prepare("SELECT * FROM profiles WHERE `username`=?")
$prep->bind_param("s",$anti_injection);
$prep->execute();
Thats all I know for the SELECT in a safe mode but then with the MYSQLI_FETCH_ARRAY I really dont know it it will work and hopefully if there is a chance to keep the script the way I like with the echos between the HTML BODY page
Some Example On How it must be done?

First off, I highly recommend you not mix procedural with objects. It will get confusing much faster that way. Consider using the mysqli object instead.
$mysqli = new mysqli('localhost'...);
Second, you're close but, as I said, you're mixing objects and procedural so the way you've changed it won't work. Plus you're bouncing variables all over the place (if you ran your changes raw it would fail). Assuming you switch to the mysqli object as outlined above, you can do this
$prep = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?");
$prep->bind_param("s",$anti_injection);
$prep->execute();
Now, the next part is tricky. You have to have mysqlnd installed to do this but it's the best way to get your results back. If you run this and get an error about get_result being missing, you're not running mysqlnd
$result = $prep->get_result();
while($row = $result->fetch_array()) {
//Your HTML loop here
}

I provide a script, based on yours, that i have commented, tested, and uses procedural 'mysqli'. Hopefully, it will clarify things.
<?php
/* (PHP 5.3.18 on XAMPP, windows XP)
*
* I will use the procedural 'mysqli' functions in this example as that is
* what you seem familiar with.
*
* However, the 'object oriented' style is preferred currently.
*
* It all works fine though :-)
*
* I recommend PDO (PHP Data Objects) as the way to go for Database access
* as it provides a 'common' interface to many database engines.
*/
// this is an example 'select' parameter -- how this value gets set is up to you...
// use a form, get parameter or other, it is not important.
$bindparamUsername = 'user_2'; // example!!!!
// connect to the database...
$dbConnection = mysqli_connect('localhost', 'test', 'test'); // connect
mysqli_select_db($dbConnection, 'testmysql'); // my test database
// the SQL Query...
// the '?' is a placeholder for a value that will be substituted when the query runs.
// Note: the ORDER of the selected Columns is important not the column names.
//
// Note: The number of selected columns is important and must match the number of
// 'result' bind variables used later.
$sql = "SELECT username, age, gender FROM profiles WHERE username = ?";
// DB engine: parse the query into an internal form that it understands
$preparedQuery = mysqli_prepare($dbConnection, $sql);
// bind an actual input PHP variable to the prepared query so the db will have all required values
// when the query is executed.
//
mysqli_stmt_bind_param($preparedQuery, 's', $bindparamUsername);
// run the query...
$success = mysqli_execute($preparedQuery);
// You can only bind which variables to store the result columns in AFTER the query has run!
//
// Now bind where any results from the query will be returned...
// There must be as many 'bind' variables as there are selected columns!
// This is because each column value from the query will be returned into the
// 'bound' PHP variable.
//
// Note: You cannot bind to an array. You must bind to an individual PHP variable.
//
// I have kept the same names but they are only of use to you.
$fetchedRow = array( 'username' => null,
'age' => null,
'gender' => null);
/*
* Note: order of columns in the query and order of destination variables in the 'bind' statement is important.
*
* i.e. $fetchedRow[username] could be replaced with variable $firstColumn,
* $fetchedRow[age] could be replaces with variable $secondColumn
* and so on...
*
* There must be as many bind variables as there are columns.
*/
mysqli_stmt_bind_result($preparedQuery, $fetchedRow['username'],
$fetchedRow['age'],
$fetchedRow['gender']);
/*
* Note: if you use the 'Object Oriented' version of 'mysqli': All of this is 'hidden'
* but still happens 'behind the scenes'!
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
<?php // each 'fetch' updates the $fetchedRow PHP variable... ?>
<?php while (mysqli_stmt_fetch($preparedQuery)): ?>
<br />
CATEGORY <?php echo $fetchedRow['username']; ?>
<br />
TITEL <?php echo $fetchedRow['age']; ?> <br />
CONTENT <?php echo $fetchedRow['gender']; ?> <br />
<?php endwhile ?>
</body>
</html>

If you'r learning I encourage you to use Object Oriented Style
The Manual is the first resource where you can find the most accurate information. Following your example:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Here you avoid the warning undefine variable if $_GET['user'] ins't set
$user = isset($_GET['user']) ? $_GET['user'] : NULL;
$row = array();
//Checking if $user is NULL
if(!empty($user)){
// Prepared statement, stage 1: prepare
if (!($stmt = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("s", $user)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
//Fetching the result
$res = $stmt->get_result();
$row = $res->fetch_assoc();
/* explicit close recommended */
$stmt->close();
}else{
//do this code if $user is null
}
//Printing out the result
echo '<pre>';
print_r($row);
echo '</pre>';

you can do it like that
$link = mysqli_connect("localhost", "my_user", "my_password", "db"); //Establishing connection to the database , this is alias of new mysqli('')
$query="SELECT * FROM profiles WHERE `username`=?";
$stmt = $link->prepare($query);
$stmt->bind_param("s",$anti_injection); // binding the parameter to it
$stmt->execute(); //Executing
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // we used MYSQLI_ASSOC flag here you also can use MYSQLI_NUM or MYSQLI_BOTH
{
//Do stuff
}

Related

How to query my table if there is an apostrophe in search term?

How can I search for a name in my table if there is an apostrophe in the name?
If I insert name with an apostrophe like Ender's Game in my search box, it gives an error.
I already tried solutions provided on stackoverflow, but I am not able to solve this.
Here is my code:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = '$string1'";
$q = mysqli_query($conn, $quer);
If there is an apostrophe in $_GET['name'], an error is shown.
How can I solve this?
Code in that form is vulnerable to SQL injection. Use mysqli::prepare instead:
$string1 = $_GET['name'];
$quer = "SELECT * FROM info WHERE name = ?";
$stmt = $conn->prepare($quer);
$stmt->bind_param('s', $string1);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$stmt->close();
var_export($result);
If you're adapting legacy, insecure code, it may be faster to use mysqli_real_escape_string. This should be reserved as a last resort, but it's there if you need it, and it's better than a regex.
The best practice that you can expect to hear over and over again from knowledgeable StackOverflow volunteers is to use prepared statements to ensure query security and reliability.
For your case, I recommend the following snippet which not only safely executes your SELECT query, but also provides informative diagnostic/debugging checkpoints throughout the process and allows you to process the resultset - represented by an multi-dimensional associative array.
$_GET['name'] = "vinay's name";
$string1 = $_GET['name'];
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT * FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} elseif (!$stmt->bind_param("s", $string1) || !$stmt->execute()) {
echo "Statement Error: " , $stmt->error; // do not show this to public
}else{
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)){
var_export($row); // do what you like here
}
}
It is important to note that using $stmt->bind_result($result) (like in Zenexer's answer) will not work (generates $result = NULL) if the info table contains more than one column (I assume it will work with one column, but I didn't test); and it will generate a Warning because of an imbalance between the number of selected columns from SELECT * and the number of nominated variables.
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement
If you want to enjoy the benefits of explicitly binding a result variable, you should specify your desired columns in the SELECT clause like this:
if (!$conn = new mysqli("host", "user", "pass", "db")) {
echo "Database Connection Error: " , $conn->connect_error; // do not show this to public
} elseif (!$stmt = $conn->prepare("SELECT id FROM info WHERE name = ?")) {
echo "Prepare Syntax Error: " , $conn->error; // do not show this to public
} else {
if (!$stmt->bind_param("s", $string1) || !$stmt->execute() || !$stmt->bind_result($id)) {
echo "Statement Error: " , $stmt->error; // do not show this to public
} else {
while ($stmt->fetch()) {
echo "<div>$id</div>";
}
}
$stmt->close();
}

Access denied for user 'root'#'localhost' (using password: NO)

I'm using a simple form to do a database query. The database is accessed via password which I've included in the code. I'm not sure why I keep hitting the error on the string escape and the undefined variable $query = htmlspecialchars($query);
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
The issue here is that you've invoked a mysqli object with your credentials, however, later you try to execute with the mysql_ procedural method. You don't have a connection there. You need to stick with the mysqli object. Furthermore, you should use prepared statements to handle your user input on SQL queries.
Remove these, we don't need to do sanitization for prepared statements:
//BYE!
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
Now let's use the mysqli object and OOP prepared methods. However, first we need to construct our like statements as our query's variables aren't executed, you can't concatenate %?% directly into the prepared() statement.
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
Now we can bind the parameters to our $stmt object.
$stmt->bind_param('ss', $query, $query);
Let's execute it now and get our data back.
$result = $stmt->execute();
Then we can loop:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
Edit
You also don't need to escape your column names with a backtick because:
They don't have - in the name
They aren't reserved special words in MySQL.
make sure your PHP version is below 7.0 as stated here:
http://php.net/manual/en/function.mysql-real-escape-string.php
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_real_escape_string()
PDO::quote()

PHP, MYSQLi query results not working with with WHERE using $_GET

I am trying to get the results of a SQL query using WHERE, whenever I use the $_GET variable it doesn't work, now I have echoed the $query variable and it shows the value of $_GET['idced'] but for some reason it doesn't do the query thus the loop doesn't show anything.
But when I manually type in the value that I want to compare, it works perfectly fine... any help would be greatly appreciated.. I also know that their might be some security issues with using GET but its a local app so it's not a concern.. heere is the code I have:
<?php
$mysqli = new mysqli("localhost", "cx", "", "cxtrack");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$idced_history = mysqli_real_escape_string($mysqli, $_GET['idced']);
//This is the query that is not working:
$query = "SELECT * FROM applications WHERE idced = $idced_history;";
if ($result = $mysqli->query($query)) {
//This loop works fine when I replace $idced_history with a value of idced
while ($row = $result->fetch_assoc()) {
$curenttime=$row["applicationposition"];
$time_ago =strtotime($curenttime);
echo "<div style='background:red; position:relative; top:2.6em; margin-bottom:1%;'>";
echo "<a href='#'>".$row["applicationposition"]."</a><br/>";
echo "Applied On: ".$row["applicationdate"]." ( ". timeAgo($time_ago) ." ) <br>";
echo "Via: ".$row["applicationtype"]."</div>";
}
$result->free();
}
$mysqli->close();
?>
sometime it not work that way.. try change to:
$query = "SELECT * FROM applications WHERE idced = ".$idced_history;
It didn't work because, idced you get from url is a string and you should spare strings from the sql query with single quotes. Otherwise, mysql act like to your variable as a table name.
try
"SELECT * FROM applications WHERE idced = '$idced_history'";

Variables from included php file

I currently have a php file with html code in it. At the beginning of the body tag im including a dbcon.php which contains a db connection, a query and a fetch_result. I now want to use those results later in the html file but i cant get it to work.
Website-file looks like this:
<html>
<head>...</head>
<body>
<?php include("dbcon.php"); ?>
...
<some html stuff>
...
<? here i want to use the data from the query ?>
...
</body></html>
The dbcon.php simply contains the connection, the query and the fetch_results.
edit:
dbcon:
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query($con,"SELECT * FROM table");
$results = mysql_fetch_array($results_query);
?>
I cant access the data in the lower part of the html file.
Your code is "right", in that you don't need anything more to access your dbcon.php variables.
But you're mixing mysql_ and mysqli_ syntax :
mysql_query take as first parameter the query, not the connexion
mysqli_query take as first parameter the connexion, and the query as second one
You should use mysqli_ :
$con = mysqli_connect("localhost:8889","user","pw","db");
$result_query = mysqli_query($con, "SELECT * FROM table");
$results = mysqli_fetch_array($results_query);
Another version, object oriented :
$mysqli = new mysqli("localhost:8889", "user", "pw", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$results = array();
if ($result_query = $mysqli->query("SELECT * FROM table")) {
$results = $result_query->fetch_array();
}
don't use mysql_ function,it is depricated.
anyway you use wrong variable name. $results_query in mysql_fetch_array($results_query) so change it to $result_query and it might work.
<?php
$con=mysql_connect("localhost:8889","user","pw","db");
$result_query = mysql_query("SELECT * FROM table");
$results = mysql_fetch_array($result_query );
?>

Learning SELECT FROM WHERE prepared statements

Can someone re-write the below code as a prepared statement?
result = mysqli_query($con,"SELECT * FROM note_system WHERE note = '$cnote'")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
$nid = $row['id'];
}
I am trying to learn prepared statements and am having trouble understanding how it works from the many examples I have found while searching. I am hoping that if I see some code I am familiar with re-written as a prepared statement that it might click for me. Please no PDO, that is too confusing for me at my current level of knowledge. Thanks.
Hello ButterDog let me walk you through PDO step by step.
Step 1)
create a file called connect.php (or what ever you want). This file will be required in each php file that requires database interactions.
Lets start also please note my comments :
?php
//We set up our database configuration
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password
// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=xxxxx;dbname=xxxxx", $username, $password); // Construct the PDO variable using $dbh
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set attributes for error reporting very IMPORTANT!
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Set this to false so you can allow the actual PDO driver to do all the work, further adding abstraction to your data interactions.
?>
Step 2) Require the connect.php please take a look :
require ('....../........./...../connect.php'); // Require the connect script that made your PDO variable $dbh
Step 3)
to start database interactions just do the following also please read the code comments. For the moment we will not worry about arrays! Get the full gyst of PDO then worry about making it easier to work with! With repetition the "long way" comes more understanding of the code. Do not cut corners to begin with, cut them once you understand what you are doing!
$query = $dbh->prepare("SELECT * FROM note_system WHERE note = :cnote"); // This will call the variable $dbh in the required file setting up your database connection and also preparing the query!
$query->bindParam(':cnote', $cnote); // This is the bread and butter of PDO named binding, this is one of the biggest selling points of PDO! Please remember that now this step will take what ever variable ($cnote) and relate that to (:cnote)
$query->execute(); // This will then take what ever $query is execute aka run a query against the database
$row = $query->fetch(PDO::FETCH_ASSOC); // Use a simple fetch and store the variables in a array
echo $row['yourvalue']; // This will take the variable above (which is a array) and call on 'yourvalue' and then echo it.
Thats all there is to PDO. Hope that helped!
Also take a look at this. That helped me so so much!
I also use this as a reference (sometimes) - The web site looks like crap but there is quality information on PDO on there. I also use this and I swear this is the last link! So after this any questions just ask, but hopefully this can turn into a little reference guide on PDO. (hopefully lol)
Use pdo:
http://php.net/manual/en/book.pdo.php
from various docs:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
This is one way to do it with PDO:
$sel = $db->prepare("SELECT * FROM note_system WHERE note=:note");
$sel->execute(array(':note' => $_POST['note']));
$notes = $sel->fetchAll(PDO::FETCH_ASSOC);
See the placeholder :note in the query in line 1, which is bound to $_POST['note'] (or any other variable for that matter) in line 2.
If I want to run that query again, with a different value as :note, I'll just call lines 2 and 3.
Displaying the results:
foreach ($notes as $note) {
echo $note['id'] . ": " . $note['text'] . "<br />";
}
This should help you on the right path...
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id FROM note_system WHERE note = ?";
$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query)) {
print "Failed to prepare statement\n";
}
else {
$note = "mynote";
mysqli_stmt_bind_param($stmt, "s", $note);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result))
{
$nid = $row['id'];
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);

Categories