What is wrong with this SQL IF Statement? - php

so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is
$comma_separated = "'Alberta','Ontario'";
This is getting passed through to the query, which looks like this:
$sql = "SELECT * FROM persons WHERE 1=1";
if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";
$sql .= " ORDER BY surname";
and then when the query runs, I get this message:
cannot run the query because: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1
But to me the query looks right, what am I missing here?
Thanks in advance.

You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:
$sql = "SELECT * FROM persons WHERE 1=1";
if (!empty($firstname)) {
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}
if (!empty($surname)) {
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}
if (!empty($province)) {
array_walk($province, function($value, $key_not_used) use ($mysqli) {
return mysqli_real_escape_string($mysqli, $value);
});
$sql .= " AND province IN ('" . implode(',', $province) . "')";
}
$sql .= " ORDER BY surname";

Your SQL contains two WHERE's.
SELECT * FROM persons WHERE 1=1
AND firstname='fn'
AND surname='sn'
AND province='p'
WHERE province IN ($comma_separated)
ORDER BY surname
Change the last bit to:
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";
Which becomes:
AND province='p'
AND province IN ('Alberta','Ontario')

Change the last part to:
if ($province)
$sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";

Related

PHP pg_query update statement

I am trying to updata a database table using pq_query in PHP. I have the following code:
$q = "UPDATE tableName SET ('data1 = " . $data1 . "', data2='" . $data2 . "') WHERE user=".$user;
$success = pg_query($q);
if (!$success) {
$errormessage = pg_last_error();
echo "Error " . $errormessage;
}
I am getting the following error message:
ERROR: syntax error at or near "'data1 = '"
LINE 1: UPDATE tableName SET ('data1 = 10', data2= 20'') WHERE user=
Replace your query with this query
$q = "UPDATE tableName SET data1 = '$data1', data2='$data2' WHERE user='$user'";
Explaination: You should pass variable in single quotes('') if your query in double quotes.
You are using a lot of quotes which it is not understood by PostgreSQL, try simply this :
$q = "UPDATE tableName SET data1 = " . $data1 . ", data2=" . $data2 . " WHERE user=".$user;
Remove those single quotes !

insert with a select statement and php variables in 1 MySQL query

i have something like this to insert data from a form to my MySQL table. is my use of select statements in the insert valid? please enlighten me.
if(isset($_POST['date']) && isset($_POST['docName']) && isset($_POST['docSpec']) && isset($_POST['time']) && isset($_POST['symptoms']) )
{
$nameOfUser = $_COOKIE['userlogin'];
$docName = $_POST['docName'];
$date = $_POST['date'];
$symptoms = $_POST['symptoms'];
$time = date('H:i:s',strtotime($_POST['time']));
$id = mt_rand(1000,9999); //generate random appointment id
$insertQuery = "insert into appointment values
($id,(select doctorid from doctors where doctorName like '$docName' ),
$date,$symptoms,
(select patientid from patient where patientFName like '$nameOfUser'), $time)";
if(mysqli_query($conn,$insertQuery)===true)
{
echo "<script>alert('success');</script>";
}
else
{
die('Invalid query: ' . mysql_error());
$message .= 'Whole query: ' . $query;
die($message);
}
}
it says invalid query. the columns in the insert statement is already in right order. can anyone help me?
You have to specify the columns that you are inserting into -
insert into appointment (col1, col2, col3, ...) values
($id,(select doctorid from doctors where doctorName like '$docName' ), $date,$symptoms,(select patientid from patient where patientFName like '$nameOfUser'),$time)";
It looks like you have 6 columns.
EDIT: This syntax may help to clear things up -
$insertQuery = "INSERT INTO `appointment` (`col1`, `col2`, `col3`,`col4`,`col5`,`col6`) ";
$insertQuery .= "VALUES (";
$insertQuery .= "'" . $id . "'";
$insertQuery .= ", '" . "(SELECT `doctorid` FROM `doctors` WHERE `doctorName` LIKE '%" . $docName . "%')" . "'";
$insertQuery .= ", '" . $date . "'";
$insertQuery .= ", '" . $symptoms . "'";
$insertQuery .= ", '" . "(SELECT `patientid` FROM `patient` WHERE `patientName` LIKE '%" . $nameOfUser . "%')" . "'";
$insertQuery .= ", '" . $time . "'";
$insertQuery .= ")";
You're also using LIKE without giving it the chance to find other elements because you're not using wildcards.

Setting up SQL queries with multiple parameters

I need to set up a SQL query with multiple parameters that are being pulled from the URL. So far I can only get it to work with the there is only one item in the URL.
My default query to pull in all the content
$sql = "SELECT ";
$sql .= "* ";
$sql .= "FROM ";
$sql .= "cms_site_content ";
$sql .= "WHERE ";
$sql .= "1";
I then check if anything was passed through the URL and retrieve it.
if (isset($_GET["d"])) {
$d=$_GET["d"];
Inside the if statement, I break the values passed as "d" into separate items
$newD = explode(',',$d);
$countD = count($newD);
foreach($newD as $discipline) {
if ($countD == 1) {
$sql .= " AND";
$sql .= " discipline='".$discipline."'";
}
My problem is getting the SQL to work if there is more than one discipline value. It should read something like this:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value"
however if there's more than one discipline value, it should read:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value OR discipline="value2" OR discipline="value3"
Is there a more efficient way to write this? I can't figure out how to insert the OR into the foreach statement.
Save all discipline values in an array;
$discipline_arr = array();
foreach($newD as $discipline) {
$discipline_arr[] = $discipline;
// by the way, don't forget to escape for sql injection
// mysql_escape_string is the depracated one, u can use that if u have no
// other choice
}
Then in your sql, add them as discipline in ('value1','value2', 'etc ...') condition (that is for strings, for numeric types it would be like discipline in (1,2,3,4, etc)
$sql = " SELECT * FROM cms_site_content WHERE 1 " .
(empty($discipline_arr) ? "" : "and
discipline in ('". implode("','" , $discipline_arr). "') ") ;
Link to escaping
http://tr1.php.net/manual/en/function.mysql-escape-string.php
Assuming the rest of your query is in tact. Simply store all of your discipline values in an array as follows, then feed the $discipline_string to your $sql query:
$discipline_ary = array('option1', 'option2', 'option3');
$discipline_string = "";
for($i=0; $i < count($discipline_ary); $i++){
$discipline_string .= " discipline = '" . $discipline[$i] . "' ";
if($i+1 == count($discipline_ary)){
break;
}else{
$discipline_string .= " OR "
}
}

PHP query does not return result

This query is not returning any result as there seems to be an issue with the sql.
$sql = "select region_description from $DB_Table where region_id='".$region_id."' and region_status =(1)";
$res = mysql_query($sql,$con) or die(mysql_error());
$result = "( ";
$row = mysql_fetch_array($res);
$result .= "\"" . $row["region_description"] . "\"";
while($row = mysql_fetch_array($res))
{
echo "<br /> In!";
$result .= " , \"" . $row["region_description"] . "\"";
}
$result .= " )";
mysql_close($con);
if ($result)
{
return $result;
}
else
{
return 0;
}
region_id is passed as 1.
I do have a record in the DB that fits the query criteria but no rows are returned when executed. I beleive the issue is in this part ,
region_id='".$region_id."'
so on using the gettype function in my php it turns out that the datatype of region_id is string not int and thus the failure of the query to function as my datatype in my tableis int. what would be the way to get parameter passed to be considered as an int in php. url below
GetRegions.php?region_id=1
Thanks
Try it like this:
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"
The region_id column seems to be an integer type, don't compare it by using single quotes.
Try dropping the ; at the end of your query.
First of all - your code is very messy. You mix variables inside string with escaping string, integers should be passed without '. Try with:
$sql = 'SELECT region_description FROM ' . $DB_Table . ' WHERE region_id = ' . $region_id . ' AND region_status = 1';
Also ; should be removed.
try this
$sql = "select region_description from $DB_Table where region_id=$region_id AND region_status = 1";
When you are comparing the field of type integer, you should not use single quote
Good Luck
Update 1
Use this.. It will work
$sql = "select region_description from " .$DB_Table. " where region_id=" .$region_id. " AND region_status = 1";
You do not need the single quotes around the region id i.e.
$sql = "SELECT region_description FROM $DB_Table WHERE region_id = $region_id AND region_status = 1"

How to put a PHP Variable into output of a SQL Query

Ok, I am querying my DB for a file. And I want to use a PHP global variable and stick it somewhere in that output using say a '$dir' in my table. Any possible way to do so?
Just use it in a string for the query like you would in any other string. eg:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $id;
Though if you do this and your variables use user input it's VERY IMPORTANT to sanitize them against SQL injection and such. The function mysql_real_escape_string() is provided for just such instances.
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
$query = "SELECT '" . $dir . "' as myVariable, userName, userpassword from users where userName = ...."
The first reply was missing some quotes:
$sql = "UPDATE TABLE x SET dir=" . $dir . " WHERE id=" . $i
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . $i
and
$sql = "UPDATE TABLE x SET dir=" . mysql_real_escape_string($dir) . " WHERE id=" . mysql_real_escape_string($id);
->
$sql = "UPDATE TABLE x SET dir='" . mysql_real_escape_string($dir) . "' WHERE id=" . mysql_real_escape_string($id);

Categories