Using a variable value as a where statement inside PDO query - php

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

Related

Full text search with mysql php

I am trying to make a search key feature. But I am not getting any result with the following query.
public function SearchKey($key,$userid)
{
$key = mysqli_real_escape_string($this->db, $key);
$userid = mysqli_real_escape_string($this->db, $userid);
$query = mysqli_query($this->db,"SELECT * FROM posts WHERE
MATCH(theKey) AGAINST('$key' IN NATURAL LANGUAGE MODE)
AND uid = '$userid' ORDER BY sgq_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($query)) {
$data[]=$row;
}
if(!empty($data)) {
return $data;
}
}
Then fetch,
$search = $Data->SearchKey($key, $userid);
if($search){
foreach($search as $data){
echo $data['theKey'];
}
}
For example if I search OK005 then I can not get any results. I tried Full-text Search functions https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
Anyone can help me here, what I am missing ?
You're using single quotes to pass your variables. These will not be expanded in your query. You're better off using a prepared statement, and use parameter/value bindings to pass the variables. This will also solve the problem of SQL injection that your code appears to be vulnerable to.
You can try something like:
// Replace comment with appropriate connection data.
$pdo = new PDO(/* your DSN etc. */);
// Your query.
$sql =
'SELECT * FROM posts WHERE ' .
'MATCH(theKey) AGAINST(? IN NATURAL LANGUAGE MODE) ' .
'AND uid = ? ORDER BY sgq_id LIMIT 5';
// Create prepared statement from query.
$statement = $pdo->prepare($sql);
// Bind the values and enforce data type.
$statement->bindValue(1, $key, PDO::PARAM_STR);
$statement->bindValue(2, $userid, PDO::PARAM_INT);
// Run query.
$statement->execute();
// Get query results.
$rows = $statement->fetchAll();
// Your magic ...

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

PHP PDO add edit update select statments

These are my PDO add, edit, delete ,select functions for my MVC pattern implementation.
I need to know if this implementation is correct using PDO.
These are Model Class functions:
public function getStudentById($id){
$stmt = $this->db->con->query("SELECT * FROM student WHERE id = '$id'");
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result;
}
public function addStudent($arrData){
$sql = " INSERT INTO student (name,age,address)".
" VALUES ('$arrData[name]','$arrData[age]','$arrData[address]')";
$stmt = $this->db->con->prepare($sql);
$stmt->execute();
return $this->db->con->lastInsertId();
}
public function editStudent($arrData){
$sql = " UPDATE student SET ".
" name='$arrData[name]',age='$arrData[age]',address='$arrData[address]'".
" WHERE id=$arrData[id] ";
$stmt = $this->db->con->prepare($sql);
$stmt->execute();
return $this->db->con->lastInsertId();
}
public function deleteStudent($id){
$stmt = $this->db->con->query("DELETE FROM student WHERE id = '$id'");
}
Correct or not, you can do it easier and safer. One of the main advantages of PDO is the support of parametrized queries, where you only write placeholders and let PDO insert the values. This will help protecting against SQL-injection, because PDO will do the correct formatting for you.
$sql = 'SELECT * FROM student WHERE id = ?';
$statement = $db->prepare($sql);
$statement->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$statement->execute();

Differences is PHP\SQL Return

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

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