Preparing SQL query - mysql

In my PHP document, I got a SQL query looking like this:
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT * FROM `objekt_t` WHERE `id`='" . $id . "'";
$row = mysqli_query($con, $q) or die(mysqli_error($con));
while($r = mysqli_fetch_assoc($row))
{
$objekt = $r;
}
}
I realize this is very unsafe practice concerning SQL injections and such, so I've been looking into prepared SQL querys, using bound parameters. Looking at bobby-tables.com I see this example query:
$stmt = $db->prepare('update people set name = ? where id = ?');
$stmt->bind_param('si',$name,$id);
$stmt->execute();
I do not understand how I should modify my current query to match the safer one using bound parameters. Any help is appreciated.

Just the same way
$mysqli = new mysqli("localhost", "my_user", "my_password", "db");
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = "SELECT some_field FROM `objekt_t` WHERE `id`= ?";
if ($stmt = $mysqli->prepare($q)) {
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
}
}
Now $result variable contains the resuts of your query.

prepared statements transmit raw data to the query so that SQL injection is not possible. There is no need to escape for real_escape_String or any other formatting functions, as this does it for you.
Example:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE Username=?");
$statement->bind_param('s',$_POST['Username']);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
I am basically binding my $_POST data directly to the query because the data is being sent as raw, so even if the query contained a form of injection, as the $_POST['username']; the query will run as normal.
IN terms of the procedure and OOP style, it's down to preference, I personlly prefer the OOP style over the other options as it's more readable.
Working with numbers:
$ID= 5;
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID=?");
$statement->bind_param('i',$ID);
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();
Or you can work with exact values directly within the statement:
$db = new mysqli ("host","user","password","database");
$statement = $db->prepare("SELECT test FROM test WHERE ID='5'");
$statement->execute();
$statement->bind_result($resultCol);
$statement->fetch();
$statement->close();

You can do it like this:
$stmt = $mysqli->prepare('SELECT * FROM objekt_t WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// $row is an associative array
}

Related

What's the best way to fetch an array

Alright, so I believe that there is a better way that I can fetch an array from the database, here's the code right now that I have.
$id = 1;
$userquery = mysql_query("SELECT * FROM login WHERE id='$id'");
while($row = mysql_fetch_array($userquery, MYSQL_ASSOC)) {
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
So If I am not wrong, you want a better way to get all the returned rows from mysql in a single statement, instead of using the while loop.
If thats the case, then I must say mysql_ drivers do not provide any such functionality, which means that you have to manually loop through them using foreach or while.
BUT, since mysql_ is already depricated, you are in luck! you can actually switch to a much better and newer mysqli_ or the PDO drivers, both of which DO actually have functions to get all the returned rows.
For mysqli_: mysqli_result::fetch_all
For PDO : PDOStatement::fetchAll
Eg.
mysqli_fetch_all($result,MYSQLI_ASSOC);
// The second argument defines what type of array should be produced
// by the function. `MYSQLI_ASSOC`,`MYSQLI_NUM`,`MYSQLI_BOTH`.
Like the comments already told you: PHP's mysql driver is deprecated. And you should use prepared statements and parameters.
for example in PDO your code would look something like this:
//connection string:
$pdo= new PDO('mysql:host=localhost;dbname=my_db', 'my_user', 'my_password');
//don't emulate prepares, we want "real" ones:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//use exception-mode if you want to use exception-handling:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = 1;
//it's always better to strictly use backticks for db-names (db, tables, fields):
$sql = "SELECT * FROM `login` WHERE `id` = :id";
try
{
//create your prepared statement:
$stmt = $pdo->prepare($sql);
//bind a parameter and explicitly use a parameter of the type integer (in this case):
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
//execute the query
$stmt->execute();
}
catch(PDOException $e)
{
exit("PDO Exception caught: " . $e->getMessage());
}
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$username = $row['username'];
$password = $row['password'];
$email = $row['email'];
}
here you go: your PHP-MySQL routine is save against SQL-injections now and no longer uses deprecated PHP-functions! it's kinda state of the art ;)

Get single parameter from joomla database

I'm trying to retrieve the image intro of an article outside the article component.
I'm using this query:
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('images')
->from('#__content')
->where('id = 151');
$db->setQuery($query);
$image = $db->loadResult();
echo $image;
The problem is the database field, where are stored many parameters, and the result of my query is this:
{"image_intro":"images\/myimage.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/myimage.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}
How can i retrieve only the "image_intro" parameter?
Firstly, don't forget to escape in your database query. I've made some changes to it for you:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('images'))
->from($db->quoteName('#__content'))
->where($db->quoteName('id') . ' = '. $db->quote('151'));
$db->setQuery($query);
$image = $db->loadResult();
You then need to json_decode the result like so
$image_intro = json_decode($image);
$path = $image_intro->image_intro;
If you use echo $path, you will get the following output:
images/image_name.jpg
You can then display the image like so:
<img src="<?php echo JUri::root() . $path; ?>" />
I would simply get the ContentModelArticle and then load the specific article ID.
/* Lets say the article ID = 151 */
$id = 151;
/* Get an instance of the generic articles model
#var ContentModelArticle $model */
$model = JModelLegacy::getInstance('Articles', 'ContentModel', array('ignore_request' => true));
$myArticle = $model->getItem($id);
/* That way you have access to all the use params as well as the image you're after */
$images = json_decode($myArticle->images);
$image_intro = $images->image_intro;
Article URLs can also be handled the same way…
$urls = json_decode($myArticle->urls);
Or Article params…
$params = $myArticle->params;
$page_heading = $params->get('page_heading');
Other useful params…
$params->get('show_publish_date');
$params->get('show_create_date');
$params->get('show_hits');
$params->get('show_category');
$params->get('show_parent_category');
$params->get('show_author');

mysql max function does not work in joomla

someone can tell me what is wrong in this code? I just want to get the last date in Joomla 2.5. Thanks
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select($db->quoteName('MAX(created)'))
->from($db->quoteName('#__content'))
$db->setQuery($query);
$result = $db->loadResult();
return $result;
don't quote functions:
$query
->select('MAX('.$db->quoteName('created').')')
->from($db->quoteName('#__content'));
A ; is missing at the end of the line ->from($db->quoteName('#__content'))

Mysql dynamic sql statement with PDO and parameters

I want to create a dynamic sql statement and run it using PDO. My problem is that i have some parameters and i cannot think of a way to pass the parameters.
Ex :
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= " AND name = ?";
if (!empty($status)) $query .= " AND status = ?"
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->bindParam (1,$name);
$db_stmt->bindParam (2,$status);
My parameters does not get binded and i don't know how many parameters i have to bind, unless i write the same if statements but with bindParam instructions.
I tryed with mysql_real_escape_string instead bindParam to PDO but for some reason my parameters are added empty.
Any idea on how can i build a dynamic query and bind parameters to PDO ?
Edit 1 :
$arr = array();
if (!empty($name)){
$query .= " AND `name` like :NAME";
$arr['NAME'] = $name;
}
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->execute($arr);
How can i write a "like" statement ? I tried
$query .= " AND `name` like :NAME" . "%";
and is not working.
What I usually do is the following:
$query = "Select * from `tbl_task` where 1=1";
$arr = array();
if (!empty($name))
{
$query .= " AND `name` = :NAME";
$arr['NAME'] = $name;
}
if (!empty($status))
{
$query .= " AND `status` = :STATUS";
$arr['STATUS'] = $status;
}
$this->db->beginTransaction();
try
{
$tmp = $this->db->prepare($query);
$tmp->execute($arr);
$this->db->commit();
}
catch(PDOException $ex)
{
$this->db->rollBack();
$this->log->error($ex->getMessage());
}
You can't add SQL code as a parameter; only data will do. You'll have to force these bits into $query. They won't be escaped then so they shouldn't contain user-submitted data.
What I usually do is the following:
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= $db->parse(" AND name = ?s", $name);
if (!empty($status)) $query .= $db->parse(" AND status = ?s",$status);
$data = $this->db->getAll($query);
the idea is in having a function to parse placeholders in arbitrary query part instead of whole query.
I don't bother with native prepared statements though. They pollute PHP scripts with heaps of useless code with not a single benefit.
To answer updated question
as you've been told, you can't bind arbitrary query part. But a literal only.
So, make your literal looks like foo% and then bind it usual way.

use a single return from a sql query

I'm using PHP to make a very specific sql query. For example sake, I have the user's ID number, but I need their name. So I do a sql query from that table with the ID number in order to return the name.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
Now I want to use that. What's the most succinct way to go about making that result into a variable ths I can use?
edit:
I'm hoping that this is not the answer:
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$username = $val;
}
}
}
I have used something like this to keep it short in the past:
list($name) = mysql_fetch_row(mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db));
echo $name;
In my opinion, the best way to fetch any SQL result is through mysql_fetch_assoc(). To use it, you would do something like this:
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
while ($row = mysql_fetch_assoc($result)) {
echo $row['name']; // You get an array with each column returned from your query.
}
Still, MySQL extension has been replaced for MySQLi, which is acknowledged to be faster and more practical. It has both OOP and structural bindings, and takes more into account your server settings.
$result = mysql_query("SELECT name FROM users WHERE userID=$thisuserid",$db);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$name = mysql_fetch_row($result)[0];
You should use MySQLi as bellow:
$db = new MySQLi($host,$user,$pass,$db);
$query = $db->query('SELECT name FROM users WHERE userID='.$thisuserid);
$result = $query->fetch_object();
echo $result->name;
If you use SELECT * so you also can access via $result->{field_name}