Learning SELECT FROM WHERE prepared statements - php

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

Related

My code does not read from mysql database

I've tried to debug this times without success. Here is what I've tried so far
<?php
$cid= (string)$_GET['cid'];//I passed this from another page using get method
echo $cid; //My code works up to this point
$record = mysql_query("select * from questions where QType = '$cid'");
$array = array();
while($row = mysql_fetch_assoc($record))
{
$array[] = $row;
}
for($var = 0; $var<count($array);$var++)
{
echo $array[$var]['Question'].'<br>';
}
?>
This code will work and is a bit safer
<?php
//Connection part
$servername = "server_adress"; //It can be localhost or 127.0.0.1 or some other IP
$username = "XXXXXX"; //Username for DB
$password = "YYYYYY"; //Password for that user
$database = "ZZZZZZ"; //DB name you are connecting to
//Create a new connection
$conn_to_db = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn_to_db -> connect_error) {
die("Connection failed: " . $conn_to_db ->connect_error);
}
//Finished connection part
$cid = mysqli_real_escape_string($conn_to_db, $_GET['cid']); //Escapes special characters in a string for use in an SQL statement
$array = array();
if($stmt = $conn_to_db -> ("SELECT * FROM questions WHERE QType = ?")) {
$stmt -> bind_param("s", $cid);
$stmt -> execute();
$stmt -> bind_result($question_from_db); //Here you can put all variables you are fetching from DB
while($stmt -> fetch()){
//Iterate over rows - put your code here to fetch everything you need from DB and put in array
$array[] = array('question' => $question_from_db);
}
$stmt -> close();
}
}
//you can iterate over rows like this
foreach($array as $key => $value) {
echo $value['question'];
}
?>
Couple of things to keep in mind:
it's a good practice to avoid * (selecting everything from DB) and
put only columns you need from DB
use prepared statement which is a safer way and protects you from SQL injection
MySQL is depreciated so try to avoid it (use mysqli or PDO)
The code above you need to adjust to your needs! It will not work as copy/paste. Put your DB connection and select columns from DB you need and add variables which you fetch from DB
Keep in mind there are more ways to do this, and someone will probably give another solution.
if you are not on a production server, it's good to have some error reporting to see the errors that are happening

PHP and MySQL mysqli->prepare keeps failing in FPDF file

Ok. I'm trying to prevent SQL injections on my first project build with FPDF.
(Since my insecure solution is working I suspect it has nothing in particular to do with FPDF. Just thought I'd mention that this is used to get data for generating a PDF :) )
The code below is working mighty fine. But it vulnerable to injections:
$mysqli = mysqli_connect('','','',''); // Empty on purpose due to posting here :)
$IDQuery = mysqli_query($mysqli,"SELECT ID FROM sendsubmits WHERE ID = $ID");
The $ID is an integer taken from the url like this:
$ID = htmlspecialchars($_GET["ID"]);
As far as I understand I need to swap $ID with ?. And then use bind_param to have it inserted.
I've tried and follow the doc here:
http://php.net/manual/en/mysqli-stmt.bind-param.php
And my result is this:
$mysqli = new mysqli('','','',''); // Empty on purpose due to posting here :)
/* Check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$IDQuery = $mysqli->prepare('SELECT ID FROM sendsubmits WHERE ID = ?');
$IDQuery = bind_param('i', $ID);
$IDQuery = execute();
printf('%d Row inserted.\n', $stmt->affected_rows);
$IDQuery->close();
This isn't working. And I can't seem to figure out why.
Any suggestions?
Not $IDQuery = bind_param('i', $ID);
but $IDQuery->bind_param('i', $ID);
The same with execute. Next time try to understand what you read in manual

mysql_query not working

Here's PHP code that I'm using:
$query="select * from `myTable` where `email`='$email' limit 0,1";
if(empty($conn))
{
echo "not connected".PHP_EOL;
}
$result = mysql_query($query,$conn);
$row = mysql_fetch_array($result);
if(empty($row))
{
....
When the query is executed in phpmyadmin, I get a single row selected.
However, when I execute the code in php, the row is always empty.
The same goes for several other queries that I've tried to execute. mysql_query always fails.
What could be wrong?
I do not feel there is enough of the code to see what is going on. But based on just what you are showing us, after you get the $result and assign it to $row you have a if statement
if(empty($row)) {...doing something secret...}
which means if something was returned like the row you are expecting NOTHING would happen because (empty($row)) would be false and not execute.
Try this using PDO:
<?php
$email = "example#example.com";
try {
//Instantiate PDO connection
$conn = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
//Make PDO errors to throw exceptions, which are easier to handle
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Make PDO to not emulate prepares, which adds to security
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = <<<MySQL
SELECT *
FROM `myTable`
WHERE `email`=:email
LIMIT 0,1;
MySQL;
//Prepare the statement
$stmt = $conn->prepare($query);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
//Work with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//Do stuff with $row
}
}
catch (PDOException $e) {
//Catch any PDOExceptions errors that were thrown during the operation
die("An error has occurred in the database: " . $e->getMessage());
}
Using mysql_* functions is highly discouraged. It's a guarantee to produce broken code. Please learn PDO or MySQLi from the links in the comment I gave you, and use those instead.
First, confirm $email's value. Echo it right before defining $query to make sure it's what you think it is.
If you've already done that, then you know that's the problem--instead, it's likely that your link identifier $conn is the problem. Instead of using a link identifier, try leaving the second parameter of your query empty, and instead run mysql_connect() at the beginning of your script. That's the best way to do things 99.5% of the time.
See: http://php.net/manual/en/function.mysql-connect.php

Trying to execute a SELECT statement in MYSQL but it is not working

I believe I have the syntax correct, at least according to my textbook. This is just a piece of the file as the other info is irrelevant to my problem. The table name is user, as well as the column name is user. I don't believe this to be the problem, as other sql statements work. Though it isn't the smartest thing to do I know :) Anyone see an error?
try {
$db=new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user,$db_pass);
} catch (PDOException $e) {
exit("Error connecting to database: " . $e->getMessage());
}
$user=$_SESSION["user"];
$pickselect = "SELECT game1 FROM user WHERE user='$user' ";
$pickedyet = $db->prepare($pickselect);
$pickedyet->execute();
echo $pickselect;
if ($pickedyet == "0")
{
echo '<form method="post" action="makepicks.php">
<h2>Game 1</h2>......'
Since you're seemingly using prepared statements, I'd recommend using them to their fullest extent so that you can avoid traditional problems like SQL injection (this is when someone passes malicious SQL code to your application, it's partially avoided by cleansing user inputs and/or using bound prepared statements).
Beyond that, you've got to actually fetch the results of your query in order to display them (assuming that's your goal). PHP has very strong documentation with good examples. Here are some links: fetchAll; prepare; bindParam.
Here is an example:
try
{
$db = new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user, $db_pass);
}
catch (PDOException $e)
{
exit('Error connecting to database: ' . $e->getMessage());
}
$user = $_SESSION['user'];
$pickedyet = $db->prepare('SELECT game1 FROM user WHERE user = :user');
/* Bind the parameter :user using bindParam - no need for quotes */
$pickedyet->bindParam(':user', $user);
$pickedyet->execute();
/* fetchAll used for example, you may want to just fetch one row (see fetch) */
$results = $pickedyet->fetchAll(PDO::FETCH_ASSOC);
/* Dump the $results variable, which should be a multi-dimensional array */
var_dump($results);
EDIT - I'm also assuming that there is a table called 'user' with a column called 'user' and another column called 'game1' (i.e. that your SQL statement is correct aside from the usage of bound parameters).
<?php
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
try
{
// nothing was wrong here - using braces is better since it remove any confusion as to what the variable name is
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e ) // catch all exceptions here just in case
{
exit( "Error connecting to database: " . $e->getMessage() );
}
// this line is unecessary unless you're using it later.
//$user = $_SESSION["user"];
// no need for a new variable here, just send it directly to the prepare method
// $pickselect = '...';
// also, I changed it to a * to get the entire record.
$statement = $db->prepare( "SELECT * FROM user WHERE user=:user" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user', $_SESSION['user'], PDO::PARAM_STR );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
echo $userRow->game1;
Change this user=$user with this user='$user'. Please, note the single quotes.
Moreover, you are executing the query $pickedyet->execute(); but then you do echo $pickselect; which is nothing different from the string that contains the query.
Little hints:
You've to retrieve the result of the query execution.
You're using prepared statement which are very good but you're not really using they because you're not doing any binding.

PDO not returning results from SELECT on more than 1 column

The server is running PHP 5.2.8. PDO has mysql 5.1.30 drivers installed.
Alright, so I am trying to figure out some PDO ( and this is just killing me. When I run the code below, I get the expected results, no problem.
However, whenever I try to add more than one column (or *) to the SELECT, there is no reply from the query - no results whatsoever. I have tried everything - I know it must be something simple. Any suggestions as to why more than one column fails to return any rows?
$hostname = "localhost";
$dbname = "dbname";
$username = "username";
$password = "password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT LastName FROM staff";
foreach ($dbh->query($sql) as $row) {
echo $row['LastName'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
Again, if I try to add columns in the statement stored in $sql to anything other than a single column, I get bupkis. For example:
SELECT FirstName, LastName FROM staff
returns zero results. Both columns exist - if requested separately, they return expected results. When combined, the query takes quite some time, then returns nothing.
No exception is caught by the catch block.
I think you have a number of issues here, mostly in your code that handles reading the values returned by the query. I have taken the liberty of changing a few things and rewriting this to use prepare statements, which is a function that PDO provides that you should take advantage of.
On prepare statements:
Why use them: http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
PHP PDO doc: http://php.net/manual/en/pdo.prepare.php
Here is the core code:
try {
//open database
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//define sql query
$sql = "SELECT LastName FROM staff";
//prepare the query for execution
$qresult = $dbh->prepare($sql);
//insert code below to handle parameters to the sql query here
//execute the query
$qresult->execute();
//fetch the results
foreach ($qresult->fetch(PDO::FETCH_ASSOC) as $row)
{
echo $row['LastName'] . '<br />';
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$qresult = null; //close the result set
$dbh = null; //close the database
Note, that I have replaced the call to query() with a couple of lines that call prepare() then execute(). You can then easily insert the following lines in between the prepare() and execute() calls to handle passing parameterized queries. This will help reduce chances of sql injection.
I have also changed the way you are accessing the retirned valued by specifying that I want them returned as and associative array, PDO::FETCH_ASSOC. This will get you a result set that you can iterate through like you would have using the old mysql interfaces.
If your query was a parameterized query like:
$sql="SELECT LastName FROM staff WHERE LastName=':lastname'";
where :lastname is the parameter.
Here is the code you would insert at the comment to handle this, (this code will handle multiple parameters. Simply add additional elements to the $param array):
//bind parameters to the prepared statement
$param = array(':lastname'=>'Jones');
foreach ($param as $key => $value) {
$qresult->bindValue($key,$value);
}
Make sure you separate the columns in the SELECT with a comma (space on either side of the comma is okay, but not required). If you want to select all columns, have only a * with no other characters.

Categories