I'm shifting my database connections from mysqli to PDO.
While updating,I'm stuck on one query:
In mysql its:
$quec='designation=10 OR designation=11 OR designation=12';
$query="select firstname,mobile,email from mt where location=".$value." and cp!=".$cpa" and (".$quec.") and dept=".$usersubdept." and mstatus=1";
Its working fine in mysqli.
In PDO i wrote:
$query="select firstname,mobile,email from mt where location=:value AND cp!=:cpa AND (:quec) AND dept=:usersubdept AND mstatus=:mstatus";
Binding the values with variables using bind syntax, I'm not getting any result row.
How to rectify the problem?
I don't think you can use :quec as a parameter, since it is actually 3 things and not a value that can be bound. Otherwise, you may have something wrong with how you're binding, perhaps, but we haven't seen your code for that. Try this:
$query="SELECT firstname, mobile, email FROM mt WHERE location = :value AND
cp != :cpa AND (" . $quec . ") AND dept = :dept AND mstatus = 1";
$stmt = $db->prepare($query);
$stmt->bindValue(':value',$value);
$stmt->bindValue(':cpa',$cpa);
$stmt->bindValue(':dept',$usersubdept);
$stmt->execute();
You need to prepare a string like this: ':id0, :id1, :id2, you can do this like this:
$designationlist = ':id'.implode(',:id', array_keys($designationIds));
then your SQL will be:
$query="select firstname,mobile,email from mt where location=:value AND cp!=:cpa AND designation IN(".$designationlist.") AND dept=:usersubdept AND mstatus=:mstatus";
and:
$parms = array_combine(explode(",", $designationlist), $designationIds);
$stmt = $PDO->prepare($query);
$res = $stmt->execute($parms);
Related
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.
This one came close to answering my question: Protect from injections and right syntax for $_GET method
However, my issue is that I am trying to combine the wildcard search %. So my original statement that works is like this which is wrapped in a try catch block.
$sql = "SELECT id, Store_name, address_line_1, city, state FROM pharmacies_weno WHERE Store_name LIKE '%".$_GET['term']."%' AND city LIKE '%".$_GET['city']."%'";
$sql .= " AND address_line_1 LIKE '%".$_GET['address']."%'";
But of course I want to make the statement like this.
$sql = "SELECT id, Store_name, address_line_1, city, state FROM pharmacies_weno WHERE Store_name LIKE ? AND city LIKE ?;
$sql .= " AND address_line_1 LIKE ? ";
With a statement like this
$stm = ('%$term%','%$city%','%$address%');
However, this is not working. I have tried all the variations of double and single quotes that I can think of along with the concatenation but nothing is working for me. I put the $_GET variables into another variable.
Yes there is other code in the program that does the binding. The final statement should look something like.
$sql = "SELECT id, Store_name, address_line_1, city, state FROM pharmacies_weno WHERE Store_name LIKE ? AND city LIKE ?;
$sql .= " AND address_line_1 LIKE ? ";
$stm = ('%$term%','%$city%','%$address%');
sqlStatement($sql,$stm); //This is where the binding takes place in the program
So what I need to know is how to use the wildcard with the variable.
if you are using PDO then i would like to do like-
$sql = "SELECT id, Store_name, address_line_1, city, state FROM pharmacies_weno
WHERE Store_name LIKE :store_name
AND city LIKE :city
AND address_line_1 LIKE :address_line_1 ";
// now prepared statement like-
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':store_name'=>'%'.$_GET['store_name'].'%',
':city'=>'%'.$_GET['city'].'%',
':address_line_1'=>'%'.$_GET['address_line_1'].'%'
));
$result=$stmt->fetchAll();
if you didnot use pdo then have a look over pdo prepared statement via php.net
I'm trying to blind my MySql query I noob in this, I want prevent to SQL Injection on my query. This is my statement but have one error
$sql = $conn ->prepare("SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE '% :name %'");
$sql-> bind_param('name', $q);
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match
number of parameters in prepared statement in
this work fine but that is a bad way
$sql="SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE '%".$q."%';
Please help me with this and what other way Can I use to protect my query in my PHP Code
Thank you for all, that was my solution
$sql = $conn ->prepare('SELECT * FROM Personas WHERE concat(nombre1," ",apellido1) LIKE ? ');
$key = "%".$q."%";
$sql-> bind_param('s', $key);
Use bind_param this way:
$sql= $conn->prepare("SELECT * FROM Personas WHERE concat(nombre1,' ',apellido1) LIKE :name");
$q= "%$q%";
$sql->bindParam(':name', $q);
$sql->execute();
The mysql documentation uses question marks (?) to indicate where a subsequent bind_param value should be placed. Try replacing ":name" with the a "?" in the query and your bind_param should follow the syntax bind_param("s", $q) where "s" is a string identifying the types of values being bound: s for string, d for decimal, i for integer, etc.
Not sure how I can do this. Basically I have variables that are populated with a combobox and then passed on to form the filters for a MQSQL query via the where clause. What I need to do is allow the combo box to be left empty by the user and then have that variable ignored in the where clause. Is this possible?
i.e., from this code. Assume that the combobox that populates $value1 is left empty, is there any way to have this ignored and only the 2nd filter applied.
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Thanks for any help.
C
Use
$where = "WHERE user_id = '$username'";
if(!empty($value1)){
$where .= "and location = '$value1'";
}
if(!empty($value2 )){
$where .= "and english_name= '$value2 '";
}
$query = "SELECT * FROM moth_sightings $where";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Several other answers mention the risk of SQL injection, and a couple explicitly mention using prepared statements, but none of them explicitly show how you might do that, which might be a big ask for a beginner.
My current preferred method of solving this problem uses a MySQL "IF" statement to check whether the parameter in question is null/empty/0 (depending on type). If it is empty, then it compares the field value against itself ( WHERE field1=field1 always returns true). If the parameter is not empty/null/zero, the field value is compared against the parameter.
So here's an example using MySQLi prepared statements (assuming $mysqli is an already-instantiated mysqli object):
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = ?
AND location = IF(? = '', location, ?)
AND english_name = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssss', $username, $value1, $value1, $value2);
$stmt->execute();
(I'm assuming that $value2 is a string based on the field name, despite the lack of quotes in OP's example SQL.)
There is no way in MySQLi to bind the same parameter to multiple placeholders within the statement, so we have to explicitly bind $value1 twice. The advantage that MySQLi has in this case is the explicit typing of the parameter - if we pass in $value1 as a string, we know that we need to compare it against the empty string ''. If $value1 were an integer value, we could explicitly declare that like so:
$stmt->bind_param('siis', $username, $value1, $value1, $value2);
and compare it against 0 instead.
Here is a PDO example using named parameters, because I think they result in much more readable code with less counting:
$sql = "SELECT *
FROM moth_sightings
WHERE user_id = :user_id
AND location = IF(:location_id = '', location, :location_id)
AND english_name = :name";
$stmt = $pdo->prepare($sql);
$params = [
':user_id' => $username,
':location_id' => $value1,
':name' => $value2
];
$stmt->execute($params);
Note that with PDO named parameters, we can refer to :location_id multiple times in the query while only having to bind it once.
if ( isset($value1) )
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND location = '$value1' AND english_name = $value2 ";
else
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' AND english_name = $value2 ";
But, you can also make a function to return the query based on the inputs you have.
And also don't forget to escape your $values before generating the query.
1.) don't use the simply mysql php extension, use either the advanced mysqli extension or the much safer PDO / MDB2 wrappers.
2.) don't specify the full statement like that (apart from that you dont even encode and escape the values given...). Instead use something like this:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s", ...);
Then fill that raw query using an array holding all values you actually get from your form:
$clause=array(
'user_id="'.$username.'"',
'location="'.$value1.'"',
'english_name="'.$value2.'"'
);
You can manipulate this array in any way, for example testing for empty values or whatever. Now just implode the array to complete the raw question from above:
sprintf("SELECT * FROM moth_sightings WHERE 1=1 AND %s",
implode(' AND ', $clause) );
Big advantage: even if the clause array is completely empty the query syntax is valid.
First, please read about SQL Injections.
Second, $r = mysql_numrows($result) should be $r = mysql_num_rows($result);
You can use IF in MySQL, something like this:
SELECT * FROM moth_sightings WHERE user_id = '$username' AND IF('$value1'!='',location = '$value1',1) AND IF('$value2'!='',english_name = '$value2',1); -- BUT PLEASE READ ABOUT SQL Injections. Your code is not safe.
Sure,
$sql = "";
if(!empty($value1))
$sql = "AND location = '{$value1}' ";
if(!empty($value2))
$sql .= "AND english_name = '{$value2}'";
$query = "SELECT * FROM moth_sightings WHERE user_id = '$username' {$sql} ";
$result = mysql_query($query) or die(mysql_error());
$r = mysql_numrows($result);
Be aware of sql injection and deprecation of mysql_*, use mysqli or PDO instead
I thought of two other ways to solve this:
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND location = '%$value1%'
AND english_name = $value2 ";
This will return results only for this user_id, where the location field contains $value1. If $value1 is empty, this will still return all rows for this user_id, blank or not.
OR
SELECT * FROM moth_sightings
WHERE
user_id = '$username'
AND (location = '$value1' OR location IS NULL OR location = '')
AND english_name = $value2 ";
This will give you all rows for this user_id that have $value1 for location or have blank values.
I am running problems in implementing LIKE in PDO
I have this query:
$query = "SELECT * FROM tbl WHERE address LIKE '%?%' OR address LIKE '%?%'";
$params = array($var1, $var2);
$stmt = $handle->prepare($query);
$stmt->execute($params);
I checked the $var1 and $var2 they contain both the words I want to search, my PDO is working fine since some of my queries SELECT INSERT they work, it's just that I am not familiar in LIKE here in PDO.
The result is none returned. Do my $query is syntactically correct?
You have to include the % signs in the $params, not in the query:
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
If you'd look at the generated query in your previous code, you'd see something like SELECT * FROM tbl WHERE address LIKE '%"foo"%' OR address LIKE '%"bar"%', because the prepared statement is quoting your values inside of an already quoted string.
Simply use the following:
$query = "SELECT * FROM tbl WHERE address LIKE CONCAT('%', :var1, '%')
OR address LIKE CONCAT('%', :var2, '%')";
$ar_val = array(':var1'=>$var1, ':var2'=>$var2);
if($sqlprep->execute($ar_val)) { ... }
No, you don't need to quote prepare placeholders. Also, include the % marks inside of your variables.
LIKE ?
And in the variable: %string%
$query = "SELECT * FROM tbl WHERE address LIKE ? OR address LIKE ?";
$params = array("%$var1%", "%$var2%");
$stmt = $handle->prepare($query);
$stmt->execute($params);
You can see below example
$title = 'PHP%';
$author = 'Bobi%';
// query
$sql = "SELECT * FROM books WHERE title like ? AND author like ? ";
$q = $conn->prepare($sql);
$q->execute(array($title,$author));
Hope it will work.