Differences is PHP\SQL Return - php

So I have two functions:
function display_name1($s){
global $db;
$query1 = "SELECT Taken From Alcohol where P_Key = $s";
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
function write_Recipe($s){
global $db;
$query1 = "SELECT Taken From Alcohol where Name = $s";
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
The only difference is that I'm matching the input "$s" with "P_Key" in the first example, and "Name" in the latter. When I put in a number for the first function, I get the appropriate return. When I put in a string that matches at least one "Name", I get nothing back. It seems to not be matches the strings for some reason. Any ideas?

There is a syntax error in the SQL query. You are missing the table name in the second query:
"SELECT Taken From where Name = '$s'"
Should be something like:
"SELECT Taken FROM `tablename` WHERE `Name` = '$s'"
Further note, that if you already using prepared statements, you should bind variables to the query instead of building the query using string concatination. Also the usage of global isn't perfect for an OOP design. Here comes an example how it can be done better:
// extend a class from PDO
class CustomPDO extends PDO {
public function display_name($s){
// use placeholder :p_key in query
$query1 = "SELECT Taken FROM `Alcohol` WHERE `P_Key` = :p_key";
$r = $this->prepare($query1);
// bind value to prepared statement
$r->execute(array(
':p_key' => $s
));
$result = $r->fetchColumn();
return $result;
}
public function write_recipe($s){
// use placeholder :name in query
$query1 = "SELECT Taken FROM `tablename` WHERE `Name` = :name";
// use $this as we are extended from PDO
$r = $this->prepare($query1);
// bind value to prepared statement
$r->execute(array(
':name' => $s
));
$result = $r->fetchColumn();
return $result;
}
}
Then use the class like a regular PDO object:
$db = new CustomPDO($connection_string, $user, $password);
But having two additional methods:
$result = $db->display_name('foo');
$result = $db->write_recipe('foo');

When querying on strings, you should surround a variable with quotes, like so:
"SELECT Taken From where Name = '$s'"
Also your second query is missing a table name.
"SELECT Taken FromTableNamewhere Name = '$s'"

Strings need to be quoted (and probably escaped if you haven't already). You seem to be using PDO, why not add a placeholder ? and execute execute(array($s)); instead, making PDO do the work for you?
function display_name1($s){
global $db;
$query1 = "SELECT Taken From Alcohol where P_Key = ?";
$r = $db->prepare($query1);
$r->execute(array($s));
$result = $r->fetchColumn();
return $result;
}
function write_Recipe($s){
global $db;
$query1 = "SELECT Taken From Alcohol where Name = ?";
$r = $db->prepare($query1);
$r->execute(array($s));
$result = $r->fetchColumn();
return $result;
}

Related

Using a variable value as a where statement inside PDO query

Lets say I have the following variable:
$where = "where `hats`='red'";
I want to inject this variable into a PDO statement. What is the proper way of doing this?
Is it like so?:
$sql = "select * from `clothing` :where";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':where', $where);
$stm->execute();
Any help would be greatly appreciated.
You can only bind values, not keywords, object names or syntactic elements. E.g., if you're always querying according to hats, you could bind the 'red' value:
$color = 'red';
$sql = "select * from `clothing` where hats = :color";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':color', $color);
$stm->execute();
If your where clause is really that dynamic, you'd have to resort to string manipulation (and face the risk of SQL injection, unfortunately):
$where = "where `hats`='red'";
$sql = "select * from `clothing` $where";
$stm = $this->app->db->prepare($sql);
$stm->execute();
// create a new PDO object by name $PDO in your connection file
In your function
function nameOfFunction($var,$value)
{
global $PDO;
$st=$PDO->prepare('SELECT * from clothing WHERE ? = ?');
$rs=$st->execute(array($var,$val));
return $st->fetchAll();
}
I hope it will work. It will return the array, Traverse it as you like

SQL query with quotes doesn't return results

I'm trying to query my sql database using PDO. There are instances in which there are quotes in my query.
function getPageByPagid($pagid) {
$db = dbConnection();
$sql = "SELECT * FROM pages WHERE pagid='".$pagid."'";
$q = $db->prepare($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$q->execute();
$results = $q->fetch();
return $results;
}
The function I'm using does prepare my SQL so that it still should work if $pagid has quotes in it. Now it is working when there aren't quotes, but it still isn't when there are quotes. Why isn't this working?
P.S.: The quotes aren't escaped or anything in my database.
May be causing you have integer type of field and sending string try with
$sql = "SELECT * FROM pages WHERE pagid='$pagid'";
or better to use placeholder (PDO standard)
function getPageByPagid($pagid) {
$db = dbConnection();
$sql = "SELECT * FROM pages WHERE pagid= :pagid";
$q = $db->prepare($sql);
$q->bindParam(':pagid', $pagid);
$q->setFetchMode(PDO::FETCH_ASSOC);
$q->execute();
$results = $q->fetch();
return $results;
}

Mysqli bind - unknown number of parameters

How to bind unknown number of parameters with Mysqli? For example, following my code:
<?php
include 'config.php';
$query = "SELECT * FROM table WHERE";
if(isset($_POST['r1']))
$query = $query." id = '$_POST['r1']'";
if(isset($_POST['r2']))
$query = $query." AND par2 = '$_POST['r2']'";
$e = mysqli_prepare($conf, $query);
?>
How to do bind of parameters?
Prepared statements probably aren't the best way to do this. You can assemble a query just as you are doing, as long as you make sure that you escape any user input. For example:
<?php
// assuming $db is a mysqli object
$query = "SELECT * FROM table WHERE";
if(isset($_POST['r1']))
$query = $query."id = '".$db->real_escape_string($_POST['r1'])."'";
if(isset($_POST['r2']))
$query = $query." AND par2 = '".$db->real_escape_string($_POST['r2'])."'";
$result = $db->query($query);
?>
Don't forget to add any required error checking.

PDO Prepared statement returns no Results

function db_execute($sql,$db,$array)
{
require(getcwd() . '/config/config.php');
if (empty($array))
{
$array = "";
print "Something wrong";
}
$connection = db_connect($db_host,$db_username,$db_password,$db);
$q = $connection->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$q ->execute(array($array));
if(!$q)
{
die("Error! " . $connection->errorInfo());
}
$result = $q -> fetchAll();
return $result;
}
$sql = "SELECT VALUE FROM users WHERE :id = :idnum";
$array = array(':id' => 'USER_ID', ':idnum' => '2');
printFormattedArray($array);
printFormattedArray(db_execute($sql,"user_db",$array));
For some reason I can't get any results from this function to return any results. But when I substitute the query with
$sql = "SELECT VALUE FROM users WHERE USER_ID = 2";
It gives me the required results. What am I doing wrong?
Basically, you have 2 choices.
.1. Refrain from using dynamical identifiers in your queries.
So, go for your second query.
$sql = "SELECT VALUE FROM users WHERE USER_ID = :idnum";
$array = array(':idnum' => '2');
$data = db_execute($sql, $array);
.2. If you need dynamical identifiers, you need a distinct placeholder for them as well
So, your code would be like
$sql = "SELECT VALUE FROM users WHERE ?n = ?i";
$data = db_execute($sql, 'USER_ID', 2);
Also,
never connect in the query execution function. Connect once and then use opened connection
always set your PDO to report mysql errors
add this code after connect
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

mysql prepared statements, is this possible?

function fetchbyId($tableName,$idName,$id){
global $connection;
$stmt = mysqli_prepare($connection, 'SELECT * FROM ? WHERE ? = ?');
var_dump($stmt);
mysqli_stmt_bind_param($stmt,'s',$tableName);
mysqli_stmt_bind_param($stmt,'s',$idName);
mysqli_stmt_bind_param($stmt,'i',$id);
$stmt = mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($name,$id);
$fetchArray = array();
while($row = mysqli_stmt_fetch($stmt)){
$fetchArray[] = $row;
}
return $fetchArray;
}
can i use the place holders for table names to or is this only possible for table columns?
No, it only accepts values (i.e.: not columns, table names, schema names and reserved words), as they will be escaped. You can do this though:
$sql = sprintf('SELECT * FROM %s WHERE %s = ?', $tableName, $idName);
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt,'i',$id);
No, you can't. Table and column names are syntax, values are data. Syntax cannot be parameterized.
The table/column name can safely be inserted into the string directly, because they come from a proven, limited set of valid table/column names (right?). Only user-supplied values should be parameters.
function fetchbyId($tableName,$idName,$id){
global $connection;
$stmt = mysqli_prepare($connection, "SELECT * FROM $tableName WHERE $idName = ?");
mysqli_stmt_bind_param($stmt,'i',$id);
$stmt = mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($name,$id);
$fetchArray = array();
while($row = mysqli_stmt_fetch($stmt)){
$fetchArray[] = $row;
}
return $fetchArray;
}

Categories