I'm trying to change this query to a query with prepared statement, but I have some problem because of conditions.
This is my basic query :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery='" . $idQuery . "'".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$result = mysqli_query($link,$sql) or die("Query (- $sql -) failed");
$count = mysqli_num_rows($result);
}
I changed it to this :
function ResponseByQuery($link,$idQuery,$Boutique=null, $agency=null){
$from_agence = "";
$req_agence = "";
$req_boutique = "";
if($Boutique!=null){
$req_boutique = " AND C.idUser ='" . $Boutique . "' ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = '". $agency."'";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =?".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$stmt->bind_param('i', $idQuery);
$result = $stmt->execute() or die("Query (- $sql -) failed");
$result = $stmt->get_result();
$count = mysqli_num_rows($result);
}
but I don't know how can I change conditions($req_boutique,$req_agence) to prepared statement?
You can replace the inlined variables in your $req_boutique and $req_agence conditions with placeholders, and then conditionally bind values to them:
if($Boutique!=null){
$req_boutique = " AND C.idUser = ? ";
}
if($agency!=null){
$from_agence = ", infos_client as IRC2";
$req_agence = " AND IRC.idClient = IRC2.idClient
AND IRC2.valueInfo = ? ";
}
$sql = "SELECT distinct(C.idClient), R.indiceRequete
FROM `infos_client` as IRC, client as C, user as U, requete as R ".$from_agence."
WHERE IRC.idQuery =? ".
$req_boutique.
"AND IRC.idCl = C.idCl
AND C.idUser=U.idUser".$req_agence;
$stmt = $link->prepare($sql);
$types = 'i';
$vars = [$idQuery];
if ($Boutique != null) {
$types .= 's';
$vars[] = $Boutique;
}
if ($agency!= null) {
$types .= 's';
$vars[] = $agency;
}
$stmt->bind_param($types, ...$vars);
Related
Currently I'm developing a search form so my SQL query needs to change with user input. Please see the below code sample.
$sqlSearch = "SELECT * FROM seafarers WHERE ";
if ($dateS != "") {
$sqlSearch .= "add_date = '" . changeDateSlashToHypen($dateS) . "' and ";
}
if ($cdcS != "") {
$sqlSearch .= "cdc = '" . $cdcS . "' and ";
}
if ($ppS != "") {
$sqlSearch .= "passport LIKE '%$ppS%' and ";
}
if ($surnameS != "") {
$sqlSearch .= "surname LIKE '" . $surnameS . "%' and ";
In order to execute this statement the user must select all the options; the statement will not work if the user selects one or two options.
Don't patch your query together like this. Use Prepared Statements. Example:
SELECT *
FROM seafarers
WHERE (:dt is null or add_date = :dt)
and (:cdc is null or cdc = :cdc)
You have to fill the parameters of the query before execution.
Start out with a placeholder like 1=1 which will always be true, and then use AND as a prefix instead of a suffix.
$sqlSearch = "SELECT * FROM seafarers WHERE 1=1 ";
if ($dateS != "") {
$sqlSearch .= " AND add_date = '" . changeDateSlashToHypen($dateS) . "'";
}
...
But as pointed out in the other answer you need to use prepared statements. So, assuming you're using mysqli, which everyone seems to do for some reason:
$sqlSearch = "SELECT * FROM seafarers WHERE 1=1 ";
$types = "";
$parameters = [];
if ($dateS != "") {
$sqlSearch .= " AND add_date = ?";
$types .= "s";
$parameters[] = changeDateSlashToHypen($dateS);
}
if ($cdcS != "") {
$sqlSearch .= " AND cdc = ?";
$types .= "s";
$parameters[] = $cdcS;
}
if ($ppS != "") {
$sqlSearch .= " AND passport LIKE ?";
$types .= "s";
$parameters[] = "%$ppS%";
}
if ($surnameS != "") {
$sqlSearch .= " AND surname LIKE ?";
$types .= "s";
$parameters[] = "$surnameS%";
}
$stmt = $db->prepare($sqlSearch);
if (count($parameters) {
$stmt->bind_param($types, ...$parameters);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
...
}
i try to insert the data with php to mysql by checking the value if it exists then it will update if no then it will insert, but it fail i use for () what is wrong with my script?
if(isset($_POST['submit'])){
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
if (empty($fieldA)) {
echo 'fieldA cannot empty';
}
else
{
for ($i=1; $i<= $nomer; $i++) {
$query = mysql_query("SELECT * FROM tb1 ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
$get1 = mysql_fetch_assoc($query);
$get2 = mysql_num_rows($query);
if ($get2 != 0) {
mysql_query("UPDATE tb1 SET kd_kelas = '2' ".
"WHERE fieldA = '$fieldA' ".
"AND fieldB = '$fieldB' ".
"AND fieldC = '$fieldC' ".
"AND fieldD = '$fieldD'");
} else {
mysql_query("INSERT INTO tb1(fieldA, fieldB, ".
"fieldC, fieldD) VALUES ".
"('$fieldA', '$fieldB', ".
"'$fieldC', '$fieldD')");
}
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}
All the methods related with mysql_* is deprecated now. Use mysqli_*.
And try this snippet:
if (isset($_POST['submit']) && !empty($_POST['fieldA'])) {
$fieldA = $_POST['fieldA'];
$fieldB = $_POST['fieldB'];
$fieldC = $_POST['fieldC'];
$fieldD = $_POST['fieldD'];
for ($i = 1; $i <= $nomer; $i++) {
$sql = sprintf("SELECT * FROM tb1 WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
$updateSql = sprintf("UPDATE tb1 SET kd_kelas = '2' WHERE fieldA = '%s' AND fieldB = '%s' AND fieldC = '%s' AND fieldD = '%s'",
$fieldA, $fieldB, $fieldC, $fieldD);
mysqli_query($link, $updateSql);
}
else {
$insertSql = sprintf("INSERT INTO tb1(fieldA, fieldB,fieldC, fieldD) VALUES ('%s','%s','%s','%s')", $fieldA,
$fieldB, $fieldC, $fieldD);
mysqli_query($link, $insertSql);
}
}
//re-direct
$go = "mydata.php";
redirect($go);
}
here $link is the connection string
$link = mysqli_connect('localhost', 'root', 'password', 'database');
I am creating dynamic query in PHP.
#$id = $_POST[id];
#$field1 = $_POST[field1];
#$field2 = $_POST[field2];
#$field3 = $_POST[field3];
$id = "id";
$field1 = "222";
$field2 = "787";
$field3 = "4444444";
$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";
$whereStr = implode(" AND ", $whereArr);
$query = "Select * from assignments WHERE {$whereStr}";
echo $query;
It is working fine.
Select * from assignments
WHERE id = id AND field1 = 222 AND field2 = 787 AND field3 = 4444444
I am getting the correct query but mysql is no longer maintained. So, I am using prepared statement like this.
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
echo $query;
Problem is how can i bind the parameters.
$stmt->bind_param("sss", $firstname, $lastname, $email);
Thanks for your advise.
You can pass the array into the execute and it will bind the values of that array.
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $pdo->prepare($query);
$stmt->execute($params);
You can see this approach on the manual as example #3. http://php.net/manual/en/pdo.prepared-statements.php
Mysqli approach:
$firstname = 'Patrick';
$lastname = 'Allaert';
$query = 'SELECT * FROM users';
$cond = array();
$params = array();
if (!empty($firstname)) {
$cond[] = "firstname = ?";
$params[] = $firstname;
}
if (!empty($lastname)) {
$cond[] = "lastname = ?";
$params[] = $lastname;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond);
}
$stmt = $mysqli->prepare($query);
if(!empty($params)) {
$n = count($params);
$a_params[] = & str_repeat('s', $n);
for($i = 0; $i < $n; $i++) {
$a_params[] = & $params[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $a_params);
}
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
print_r($row);
}
No need for arrays in your script
you can use script like below:
$where = " 1=1";
if($id != "") $where .= " and id = $id ";
if($field1 != "") $where .= " and field1 = '" . $field1 . "' ";
if($field2 != "") $where .= " and field2 = '" . $field2 . "' ";
if($field3 != "") $where .= " and field3 = '" . $field3 . "' ";
$query = "Select * from assignments WHERE $where";
echo $query;
I am listing the users who have registered in users table. But i want to hide name 'SuperAdmin' in name column.
My query is like this
$sql = "SELECT u.rowid, u.name, u.firstname, u.email, u.job, u.signature, u.office_phone, u.office_fax, u.user_mobile,";
$sql.= " u.admin, u.login, u.webcal_login, u.phenix_login, u.phenix_pass, u.note,";
$sql.= " u.pass, u.pass_crypted, u.pass_temp,";
$sql.= " u.fk_societe, u.fk_socpeople, u.fk_member, u.ldap_sid,";
$sql.= " u.statut, u.lang, u.entity,";
$sql.= " u.datec as datec,";
$sql.= " u.tms as datem,";
$sql.= " u.datelastlogin as datel,";
$sql.= " u.datepreviouslogin as datep,";
$sql.= " u.photo as photo,";
$sql.= " u.openid as openid,";
$sql.= " u.ref_int, u.ref_ext";
$sql.= " FROM ".MAIN_DB_PREFIX."user as u";
if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode))
{
$sql.= " WHERE u.entity IS NOT NULL";
}
else
{
$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
}
if ($sid) // permet une recherche du user par son SID ActiveDirectory ou Samba
{
$sql.= " AND (u.ldap_sid = '".$sid."' OR u.login = '".$this->db->escape($login)."') LIMIT 1";
}
else if ($login)
{
$sql.= " AND u.login = '".$this->db->escape($login)."'";
}
else
{
$sql.= " AND u.rowid = ".$id;
}
dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
$result = $this->db->query($sql);
if ($result)
{
$obj = $this->db->fetch_object($result);
if ($obj)
{
$this->id = $obj->rowid;
$this->ref = $obj->rowid;
$this->ref_int = $obj->ref_int;
$this->ref_ext = $obj->ref_ext;
$this->ldap_sid = $obj->ldap_sid;
$this->nom = $obj->name; // TODO deprecated
$this->lastname = $obj->name;
$this->prenom = $obj->firstname; // TODO deprecated
$this->firstname = $obj->firstname;
$this->login = $obj->login;
$this->pass_indatabase = $obj->pass;
$this->pass_indatabase_crypted = $obj->pass_crypted;
$this->pass = $obj->pass;
$this->pass_temp = $obj->pass_temp;
$this->office_phone = $obj->office_phone;
$this->office_fax = $obj->office_fax;
$this->user_mobile = $obj->user_mobile;
$this->email = $obj->email;
$this->job = $obj->job;
$this->signature = $obj->signature;
$this->admin = $obj->admin;
$this->note = $obj->note;
$this->statut = $obj->statut;
$this->photo = $obj->photo;
$this->openid = $obj->openid;
$this->lang = $obj->lang;
$this->entity = $obj->entity;
$this->datec = $this->db->jdate($obj->datec);
$this->datem = $this->db->jdate($obj->datem);
$this->datelastlogin = $this->db->jdate($obj->datel);
$this->datepreviouslogin = $this->db->jdate($obj->datep);
$this->webcal_login = $obj->webcal_login;
$this->phenix_login = $obj->phenix_login;
$this->phenix_pass_crypted = $obj->phenix_pass;
$this->societe_id = $obj->fk_societe;
$this->contact_id = $obj->fk_socpeople;
$this->fk_member = $obj->fk_member;
if (! $this->lang) $this->lang='fr_FR';
$this->db->free($result);
is it possible to do it with UNION method, someone help me in this. I tried adding Where Distinct but it didn't work. I just want to hide the name SuperAdmin
One WHERE condition will do:
$sql .= " WHERE `u`.`name` <> 'SuperAdmin';";
This will fetch all values except when name = 'SuperAdmin';
Add this after the FROM line
$sql.= " WHERE u.name != 'SuperAdmin'";
You can add a WHERE condition at the end of your query like this
$sql .= " WHERE u.name NOT LIKE 'SuperAdmin' ";
I asked this question in http://codereview.stackexchange.com and they wanted me to post it here. I couldn't get this code to work at all. I switched from regular mysql to pdo which is more safer. Could someone tell me what I'm missing here. I've been struggling with it for couple of day, and I could find exact answer when I first searched this site.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(), true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = (" SELECT * FROM classified ");
$cond = array();
$params = array();
if (!empty($input)) {
$cond[] = "title = ?";
$params[] = $input;
}
if (!empty($categories)) {
$cond[] = "id_cat = ?";
$params[] = $categories;
}
if (!empty($state)) {
$cond[] = "id_state = ?";
$params[] = $state;
}
if (!empty($zipcode)) {
$cond[] = "zipcode = ?";
$params[] = $zipcode;
}
if (count($cond)) {
$query .= ' WHERE ' . implode(' AND ', $cond)or
die(print_r($query->errorInfo(),true));
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$ro = $stmt->fetch(PDO::FETCH_NUM);
}
if ($ro > 0) {
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}
I think it's a good idea to post an answer here rather than posting a link. I'm sure it will be useful for some people.
$input = $_POST['input'];
$categories = $_POST['category'];
$state = $_POST['state'];
$zipcode = $_POST['zipcode'];
$qq = $db->prepare(" SELECT * FROM classified ")or die(print_r($qq->errorInfo(),
true));
/*** execute the prepared statement ***/
$qq->execute();
/*** echo number of columns ***/
$rows = $qq->fetch(PDO::FETCH_NUM);
if ($rows>0){
$query = " SELECT * FROM classified where confirm='0' ";
if(!empty( $_POST['input'])) {
$query .= "AND title LIKE '%".$input."%' ";
}
if (!empty($_POST['category']) )
{
$query .= "AND id_cat = ".$categories." ";
}
if (!empty($_POST['state']) )
{
$query .= "AND id_state = ".$state." ";
}
if(!empty($_POST['zipcode'])) {
$query .= "AND zipcode = ".$zipcode." ";
}
$query .= "ORDER BY date ";
}
$stmt = $db->prepare($query);
$stmt->execute($params);
$result = $stmt->fetchAll();
// $ro = $stmt->fetch(PDO::FETCH_NUM);
// it didn't work when I tried to count rows
if ($result > 0) {
foreach ($result as $row)
{
echo $row['title'];
echo $row['categories'];
echo $row['state'];
echo $row['zipcode'];
}
}else{
echo " No data available";
}