How do i bind values to a variable which is partially processed with diffrent statements and then concatenated using php .= method
Please note that I am not using array to bind parameters.
below is piece of code
$wher = '';
now I have added few varibles to $wher like
if (!empty($_SESSION['advs']['title']))
{
$wher .= '(';
if (isset($_SESSION['advs']['desc']))
{
$wher .= "(au.description like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%') OR ";
}
$wher .= "(au.title like '%" . $system->cleanvars($_SESSION['advs']['title']) . "%' OR au.id = " . intval($_SESSION['advs']['title']) . ")) AND ";
}
more addition to $wher
if (isset($_SESSION['advs']['buyitnow']))
{
$wher .= "(au.buy_now > 0 AND (au.bn_only = 'y' OR au.bn_only = 'n' && (au.num_bids = 0 OR (au.reserve_price > 0 AND au.current_bid < au.reserve_price)))) AND ";
}
if (isset($_SESSION['advs']['buyitnowonly']))
{
$wher .= "(au.bn_only = 'y') AND ";
}
if (!empty($_SESSION['advs']['zipcode']))
{
$userjoin = "LEFT JOIN " . $DBPrefix . "users u ON (u.id = au.user)";
$wher .= "(u.zip LIKE '%" . $system->cleanvars($_SESSION['advs']['zipcode']) . "%') AND ";
}
now I am using $wher in database query like
// get total number of records
$query = "SELECT count(*) AS total FROM " . $DBPrefix . "auctions au
" . $userjoin . "
WHERE au.suspended = 0
AND ".$wher . $ora . "
au.starts <= " . $NOW . "
ORDER BY " . $by;
$wher is being used in SQL select query.
How do I put placeholders to $wher and bind the values??
my problem is something like PHP PDO binding variables to a string while concatenating it
But slight different way
Related
I've tried to look for a solution but can't seem to grasp the issue I have.
I have a search query with a "where clause" stating if a user inputs multiple words return the result.
I need the result returned in the same order searched.
Even if i just add the addition "ORDER BY DESC" an error is thrown "Trying to get property of non-object".
Here is my code:
$word = $_GET['word'];
$word3 = $_GET['word'];
$word = explode(";", $word);
$noOfWords = count($word);
$word2 = $word3;
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3)
"%'";
} else {
$searchString = $whereClause = "";
foreach ($word as $entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "' ORDER BY '" . $word2 . "' ";
}
}
$whereClause = ($searchString != "") ? " WHERE " . preg_replace('/OR/',
'', $searchString, 1) : $whereClause;
$sql = "SELECT word_eng FROM words " . $whereClause . " LIMIT 17";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$row1 = $row["word_eng"];
echo $row1;
}
There are a couple of problems with the way your trying to use ORDER BY. There should be only 1 order by clause in any SQL, you are adding it in for each word your adding. The second part is that it's expecting to order by a column name and your ordering it by the words your searching for.
With wanting to maintain the order of the terms and the order of the results, it would be necessary to use an order by clause with something like a case (Can you add an if statement in ORDER BY? may help explain this).
$orderBy = "";
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3) ."%'";
} else {
$searchString = $whereClause = "";
$orderBy = " order by case `word_eng` ";
foreach ($word as $order=>$entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "'";
$orderBy .= " when '$entry' then $order ";
}
$orderBy .= " end ";
}
$whereClause = ($searchString != "") ? " WHERE " . preg_replace('/OR/',
'', $searchString, 1) : $whereClause;
$sql = "SELECT word_eng FROM words " . $whereClause . " " .$orderBy." LIMIT 17";
if ($noOfWords == 1) {
$searchString = " word_eng LIKE '" . $conn->escape_string($word3)
"%'";
} else {
$searchString = $whereClause = "";
foreach ($word as $entry) {
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry);
}
$searchString .= "' ORDER BY '" . $word2 . "' ";
}
I think you messed up with MySQL Query string in bellow line code.
$searchString .= " OR word_eng LIKE '" . $conn->escape_string($entry) . "' ORDER BY '" . $word2 . "' ";
Your Query is generating Something like
ORDER BY DESC
And OrderBy Query should be something like this
ORDER BY expression [ ASC | DESC ];
So you are missing the expression in query.
I'm writing some html+php code but this part seems to be causing error. Do you see something wrong?
$sql = "SELECT p.seccio_id, count(*), sum(r.preu)
FROM report r, persona p
WHERE r.usuari_upc = p.persona_id
and r.any = " . $_POST["any"] . "
and r.mes = " . $_POST["mes"] . "
and p.any_id = '"
if ($_POST["mes"] < 9) echo ($_POST["any"] - 1) . "-" . $_POST["any"] . "'";
else echo $_POST["any"] "-" . ($_POST["any"] + 1) . "'";
"GROUP BY p.seccio_id
ORDER BY p.seccio_id";
You have to split it up:
$sql = "SELECT p.seccio_id, count(*), sum(r.preu) FROM report r, persona p WHERE .usuari_upc = p.persona_id and r.any = " . $_POST["any"] . " and r.mes = " . _POST["mes"] . " and p.any_id = '";
if ($_POST["mes"] < 9)
$sql .= ($_POST["any"] - 1) . "-" . $_POST["any"] . "'";
else
$sql .= $_POST["any"] "-" . ($_POST["any"] + 1) . "'";
$sql .= " GROUP BY p.seccio_id ORDER BY p.seccio_id";
P.S. Your sql is vulenarable to SQL injection.
I'm having some trouble passing a number to a GET sting in php, using a urlencode and then urldecode (have tried both the standard urlencode and rawurlencode). The problem is limited to numerical values, as my code works fine for everything else.
Here are relevant sections of code:
if (isset($_GET['q'])) {
$qry = $_GET['q'];
$qry = urldecode($qry);
}
This is the code used for searching:
$qry = "SELECT * FROM jobs JOIN clients ON jobs.Client = clients.ClientCode WHERE JobNumber LIKE '%1%'";
if (isset($_GET['DP']) && (strlen($_GET['DP']) > 0)) {
$qry .= " AND DP LIKE %" . $_GET['DP'] . "%";
} elseif (isset($_POST['DP']) && (strlen($_POST['DP']) > 0)) {
$qry .= " AND DP LIKE '%" . $_POST['DP'] . "%'";
}
if (isset($_GET['JobDescription'])) {
$qry .= " AND JobDescription LIKE '%" . $_GET['JobDescription'] . "%'";
} elseif (isset($_POST['JobDescription']) && (strlen($_POST['JobDescription']) > 0)) {
$qry .= " AND JobDescription LIKE '%" . $_POST['JobDescription'] . "%'";
}
if (isset($_GET['JobNumber'])) {
$qry .= " AND JobNumber LIKE '%" . $_GET['JobNumber'] . "%'";
} elseif (isset($_POST['JobNumber']) && (strlen($_POST['JobNumber']) > 0)) {
$qry .= " AND JobNumber LIKE '%" . $_POST['JobNumber'] . "%'";
}
This is the code used to encode the query after it has been processed:
$qry = urlencode($qry);
A string is output to be used in the pagination, an example being
http://localhost/cpc/jobsearch.php?page=2&q=SELECT+%2A+FROM+jobs+JOIN+clients+ON+jobs.Client+%3D+clients.ClientCode+WHERE+JobNumber+LIKE+%27%251%25%27+AND+DP+LIKE+%27%25754611%25%27
This is causing errors around the 754611 section of the url, and the page does not preform as intended. I believe it has something to do with the %25 (which represents a % sign, and is needed for the search) running into the value (754611 in this case) and not being decoded properly.
What am I doing wrong?
I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;
I'm doing a MySQL query to search for items in a database. I've pulled variables out of the search form but I'm having some problems with my WHERE clause. As I don't want to search on fields that haven't been input in the form. The code I have at the minute is:
$query = " SELECT RequestID, clients.ClientName, clients.Username, RequestAssignee, requests.StatusID, requests.PriorityID, StatusName, PriorityName
FROM requests
INNER JOIN clients ON requests.ClientID = clients.ClientID
INNER JOIN statuses ON requests.StatusID = statuses.StatusID
INNER JOIN priorities ON requests.PriorityID = priorities.PriorityID
WHERE ";
if(!empty($RequestID))
{
$query2 .= "RequestID = '" . $RequestID . "' OR ";
}
if(!empty($ClientName))
{
$query2 .= "clients.ClientName = '" . $ClientName ."' OR ";
}
if(!empty($Username))
{
$query2 .= "clients.Username = '" . $Username . "' OR ";
}
if(!empty($RequestAssignee))
{
$query2 .= "RequestAssignee = '" . $RequestAssignee . "' OR ";
}
if(!empty($Status))
{
$query2 .= "statuses.StatusName = '" . $Status ."' OR ";
}
if(!empty($Priority))
{
$query2 .= "priorities.PriorityName = '" . $Priority ."'";
}
However you can see an issue whereby if someone only searches one field, the query adds an 'OR' to the end, resulting in an error:
SELECT RequestID, clients.ClientName, clients.Username, RequestAssignee, requests.StatusID, requests.PriorityID, StatusName, PriorityName FROM requests INNER JOIN clients ON requests.ClientID = clients.ClientID INNER JOIN statuses ON requests.StatusID = statuses.StatusID INNER JOIN priorities ON requests.PriorityID = priorities.PriorityID WHERE RequestID = '3' OR
Im guessing I'm going to have to put some sort of loop or counter in but unsure how to approach it. Any ideas?
Thanks, Matt.
$parts = array();
if(!empty($RequestID))
{
$parts[] = "RequestID = '" . $RequestID . "' ";
}
if(!empty($ClientName))
{
$parts[] = "clients.ClientName = '" . $ClientName ."' ";
}
if(!empty($Username))
{
$parts[] = "clients.Username = '" . $Username . "' ";
}
if(!empty($RequestAssignee))
{
$parts[] = "RequestAssignee = '" . $RequestAssignee . "' ";
}
if(!empty($Status))
{
$parts[] = "statuses.StatusName = '" . $Status ."' ";
}
if(!empty($Priority))
{
$parts[] = "priorities.PriorityName = '" . $Priority ."' ";
}
$query2 .= implode(' OR ', $parts);
Ok so the way i would approach this is to build the variables that will form your where clause separatley:
This could be done in an array:
FIELD1=>'Value1';
FIELD2=>'Value2';
I would then loop over this array, for the first element, i=1 i would build in a WHERE, for i+n -> i+(n-1) i would pre-pend an OR, for the last array value i wouldn't do anything.
I can then use the string i build in this loop - to stick into my query string.
Have a go at something like this and give us a shout if you need more help. Doing it this way is slightly more maintainable also.