I'm currently in the process of creating a very simple search feature for a website in which the user is able to search a database for events using a number of different criteria (from one to many, varied number) and I'm experiencing an issue with the prepared statement I'm using, the bind_param() in particularly.
Here is the relevant PHP code:
...
...
$title = (empty($_POST['eventTitle'])) ? null : $_POST['eventTitle'];
$venue = (empty($_POST['venue'])) ? null : $_POST['venue'];
$catID = (empty($_POST['catID'])) ? null : $_POST['catID'];
$start = (empty($_POST['start'])) ? null : $_POST['start'];
$end = (empty($_POST['end'])) ? null : $_POST['end'];
$price = (empty($_POST['price'])) ? null : $_POST['price'];
include 'database_conn.php';
$sql = 'SELECT eventID, eventTitle, venueID, catID, eventStartDate,
eventEndDate, eventPrice FROM te_events WHERE 1';
$sqlCondition = '';
$bindFirstArg = '"';
$bindSecondArg = '';
if($title !== null && !empty($title)) {
$sqlCondition = $sqlCondition . " AND eventTitle LIKE \"%"
. $title . "%\"";
}
if($venue !== null && $venue !== '0') {
$sqlCondition = $sqlCondition . " AND venueID=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $venue;
}
if($catID !== null && $catID !== '0') {
$sqlCondition = $sqlCondition . " AND catID=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $catID;
}
if($start !== null && $start !== '0') {
$sqlCondition = $sqlCondition . " AND eventStartDate=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $start;
}
if($end !== null && $end !== '0') {
$sqlCondition = $sqlCondition . " AND eventEndDate=?";
$bindFirstArg = $bindFirstArg . "s";
$bindSecondArg = $bindSecondArg . ", " . $end;
}
if($price !== null && !empty($price)) {
$sqlCondition = $sqlCondition . " AND eventPrice=?";
$bindFirstArg = $bindFirstArg . "i";
$bindSecondArg = $bindSecondArg . ", " . $price;
}
$sql = $sql . $sqlCondition;
$bindFirstArg = $bindFirstArg . '"';
$search_stmt = $conn -> prepare($sql);
if (false===$search_stmt) {
die('prepare() failed: ' . htmlspecialchars($conn->error));
}
$search_stmt -> bind_param($bindFirstArg, $bindSecondArg);
$search_stmt -> execute();
$search_stmt -> bind_result($eventIDRes, $eventTitleRes, $venueIDRes,
$catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
while ($search_stmt->fetch()) {
printf ("%s %s %s %s %s %s %i\n", $eventIDRes, $eventTitleRes,
$venueIDRes, $catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
}
mysqli_stmt_close($search_stmt);
The error I'm receiving states
Warning: mysqli_stmt::bind_param() [mysqli-stmt.bind-param]: Number of elements in type definition string doesn't match number of bind variables in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_w12019212/public_html/webdev/searchresult.php on line 101"
Any ideas?
You need to pass bind_param a separate argument for each ? in your query, as well as the formats as the first parameter. You can't pass it a comma-separated string, that won't work. It just reads that as the first ? and then complains that you didn't send it the rest.
Also, don't add quotes inside your $bindFirstArg string. bind_param just wants a list of all the data types (i, d, s, or b) , it doesn't want " characters.
What you need to do is push your values into an array, then call bind_param via call_user_func_array.
$sqlCondition = '';
$bindFirstArg = '';
$bindParams = array();
// You need to bind $title as well, otherwise you are wide open to SQL
// injection and have just thrown out the benefits of prepared statements
if($title !== null && !empty($title)) {
$sqlCondition .= " AND eventTitle LIKE ?";
$bindFirstArg .= "s";
// Add the `%` to the value, not the query
$title = "%{$title}%";
// bind_param wants these to be references
$bindParams[] =& $title;
}
// Change all your ifs to look like this.
// They need to push into the $bindParams array
if($catID !== null && $catID !== '0') {
$sqlCondition .= " AND catID=?";
$bindFirstArg .= "s";
// bind_param wants these to be references
$bindParams[] =& $catID;
}
// etc...
$sql .= $sqlCondition;
$search_stmt = $conn->prepare($sql);
// Call bind_param with the correct number of parameters
array_unshift($bindParams, $bindFirstArg);
// This will make sure the parameters are passed correctly.
// Each variable needs to be passed as a separate parameter
call_user_func_array(array($search_stmt, 'bind_param'), $bindParams);
$search_stmt->execute();
$search_stmt->bind_result($eventIDRes, $eventTitleRes, $venueIDRes,
$catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
while ($search_stmt->fetch()) {
printf ("%s %s %s %s %s %s %i\n", $eventIDRes, $eventTitleRes,
$venueIDRes, $catIDRes, $eventStartRes, $eventEndRes, $eventPriceRes);
}
$search_stmt->close();
Related
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
if (isset($_GET["idSubtype"]) || isset($_GET["idReference"]) || isset($_GET["dateStart"])) {
if (isset($_GET['idSubtype']) ? $idSubtype = $_GET['idSubtype'] : $dateSearch = '') {
$value = "AND subtypecrop.id = " . $idSubtype ."";
}
if (isset($_GET['idReference']) ? $idReference = $_GET['idReference'] : $dateSearch = '') {
$value = "AND reference.id = " . $idReference . " " . $value;
}
if (isset($_GET['dateStart']) ? $dateSearch = $_GET['dateStart'] : $dateSearch = '') {
$value = "AND dealing.date = ' " . $dateSearch . " ' " . $value;
}
$query = "SELECT dealing.id, type.nameType, subtypecrop.nameSubtype, dealing.date, dealing.price, unit.nameUnit, location.nameLocation, province.nameProvince, reference.nameReference, dealing.other, dealing.url
FROM dealing
JOIN unit ON unit.id = dealing.unit_id
JOIN subtypecrop ON subtypecrop.id = dealing.subTypeCrop_id
JOIN type ON type.id = subtypecrop.type_id
JOIN location ON location.id = dealing.location_id
JOIN province ON province.id = location.province_id
JOIN reference ON reference.id = dealing.reference_id
WHERE type.id = 1 " . $value . "";
// echo $query;
} else {
$query = "SELECT dealing.id, type.nameType, subtypecrop.nameSubtype, dealing.date, dealing.price, unit.nameUnit, location.nameLocation, province.nameProvince, reference.nameReference, dealing.other, dealing.url
FROM dealing
JOIN unit ON unit.id = dealing.unit_id
JOIN subtypecrop ON subtypecrop.id = dealing.subTypeCrop_id
JOIN type ON type.id = subtypecrop.type_id
JOIN location ON location.id = dealing.location_id
JOIN province ON province.id = location.province_id
JOIN reference ON reference.id = dealing.reference_id
WHERE type.id = 1;";
}
One possible problem is with:
if (isset($_GET['dateStart']) ? $dateSearch = $_GET['dateStart'] : $dateSearch = '') {
$value = "AND dealing.date = ' " . $dateSearch . " ' " . $value;
}
It should be:
if (isset($_GET['dateStart']) ? $dateSearch = $_GET['dateStart'] : $dateSearch = '') {
$value = "AND dealing.date = '" . $dateSearch . "' " . $value;
}
But the extra space wouldn't cause a syntax error.
Also, your code is suseptable to SQL Injection. You should be using prepared statements. That will take care of quoting values and prevent SQL Injection.
Try to put a space before the AND clause, because you don't have space and when you concatenate you may get an error. I would write it this way:
if (isset($_GET["idSubtype"]) || isset($_GET["idReference"]) || isset($_GET["dateStart"])) {
$value="";
if (isset($_GET['idSubtype']) ? $idSubtype = $_GET['idSubtype'] : $dateSearch = '') {
$value = " AND subtypecrop.id = " . $idSubtype;
}
if (isset($_GET['idReference']) ? $idReference = $_GET['idReference'] : $dateSearch = '') {
$value = $value." AND reference.id = " . $idReference ;
}
if (isset($_GET['dateStart']) ? $dateSearch = $_GET['dateStart'] : $dateSearch = '') {
$value = $value." AND dealing.date = '" . $dateSearch ."'" ;
}
I am a complete noob in php and trying to learn it by working on a premade script and making changes to it. I have been trying to figure out how to display titles by their first letters in a table. I went through this site http://www.emirplicanic.com/php/php-a-to-z-sorting-script but wasn't able to make it work in the script.
public function getProducts()
{
global $db, $core, $pager;
require_once(BASEPATH . "lib/class_paginate.php");
$pager = new Paginator();
$pager = new Paginator();
$counter = countEntries($this->pTable);
$pager->items_total = $counter;
$pager->default_ipp = $core->perpage;
$pager->paginate();
if ($counter == 0) {
$pager->limit = "";
}
if (isset($_GET['sort'])) {
list($sort, $order) = explode("-", $_GET['sort']);
$sort = sanitize($sort);
$order = sanitize($order);
if (in_array($sort, array("title", "cid", "price", "created"))) {
$ord = ($order == 'DESC') ? " DESC" : " ASC";
$sorting = " p." . $sort . $ord;
} else {
$sorting = " p.created DESC";
}
} else {
$sorting = " p.created DESC";
}
----------added by me-----------------
if (isset($_GET['letter'])) {
list($letter, $order1) = explode("-", $_GET['letter']);
$letter = sanitize($letter);
$order1 = sanitize($order1);
// if (in_array($sort, "A", "B", "C", "D"))) {
if (!(strcmp($letter, "A"))) {
$ord1 = ($order1 == 'DESC') ? " DESC" : " ASC";
$sorting1 = " p." . $letter . $ord1;
}
}
------------------------------------------------------------------
$sql = "SELECT p.*, p.id as pid, c.name, c.id as cid,"
. "\n DATE_FORMAT(p.created, '" . $core->short_date . "') as cdate,"
. "\n (SELECT COUNT(pid) FROM transactions WHERE pid = p.id) as sales"
. "\n FROM " . $this->pTable . " as p"
. "\n LEFT JOIN categories as c ON c.id = p.cid"
. "\n ORDER BY " . $sorting . $pager->limit;
$row = $db->fetch_all($sql);
return ($row) ? $row : 0;
}
and then the html part of it is
<li><span>A</span></li>
<li><span>B</span></li>
.
.
.
The php part is giving me an Undefined offset error. Also i am not sure if i have to add anything extra on the html to make it work
The URLS in your HTML should be ?letter=A-DESC. (or ASC) The list($letter, $order1) is expecting two results from the call to explode('-', $_GET['letter']), and it's only getting one. Thus, an 'undefined offset' in the array returned from explode().
Note that anyone can send anything in the ?letter part of the URL, not just what's in your links. You should "sanitize" (whatever that does for you) any input arguments as the very first step, and handle the situation where the data isn't what you expect before you start processing that data.
Using Joomla, having issues trying to build a mySQL query based on URL arguments. The code I have looks like this:
$db =& JFactory::getDBO();
$hpprice = JRequest::getVar('hprice');
$lprice = JRequest::getVar('lprice');
$city = JRequest::getVar('city');
$zip = JRequest::getVar('zip');
$bdrms = JRequest::getVar('bdrms');
$bths = JRequest::getVar('bths');
$query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1";
$clauses = array();
if ($zip != null) {
$clauses[] = $db->nameQuote('MSTZIP') . " = " . $db->quote($zip);
}
if ($city != null) {
$clauses[] = $db->nameQuote('MSTCITY') . " = '" . $db->quote($city) . "'";
}
if ($bdrms != null){
$clauses[] = $db->nameQuote('MSTBDRMS')." >= ".$db->quote($bdrms);
}
if ($bths != null){
$clauses[] = $db->nameQuote('MSTBATHS') . " >= " . $db->quote($bths);
}
if ($lprice != null){
$clauses[] = $db->nameQuote('MSTLISTPRC') . " BETWEEN " . $db->quote($lprice) . " AND " . $db->quote($hprice);
}
$query .= implode(" AND ", $clauses);
$db->setQuery($query);
$table = $db->loadRowList();
return $table;
So, as you can see it, adds arguments to the mySQL query based on whether or not arugments exist in the URL. What I can't wrap my head around is building the array and imploding it.
Whenever I put an argument in the URL, all the table items populate. When I try to pass an argument, it comes up null. You can see this in action here. If you add another argument like zip to the URL, everything comes up NULL.
I think the problem is this " WHERE 1=1".try to change this to this-" WHERE 1=1 ".
Because the final query will be appended to this and you'll not get the desire result.For confirmation also echo $query see if it's a correct query.one more thing is '" . $db->quote($city) . "'".remove '' as you are already adding this by a function.
//Update:
Better to use where method
Let me know if this does not work.
Not sure how this is diffent than your previous question.
$query->select('*");
$query->from($db->nameQuote('#__mls'));
$query->where('1 = 1', AND);
if ($zip != null)
{
$query->where (.$db->nameQuote('MSTZIP')." = ".$db->quote($zip));
}
if ($city != null)
{
$query->where($db->nameQuote('MSTCITY')." = '".$db->quote($city));
}
Etc
There is no need for you to build any array; that it the whole point of having a databasequery api.
Final script ended up looking like this:
$db =& JFactory::getDBO();
$hprice = JRequest::getVar('hprice');
$lprice = JRequest::getVar('lprice');
$city = JRequest::getVar('city');
$zip = JRequest::getVar('zip');
$bdrms = JRequest::getVar('bdrms');
$bths = JRequest::getVar('bths');
$query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1 AND ";
$clauses = array();
if ($zip != null) {
$clauses[] = "MSTZIP = " . $zip;
}
if ($city != null) {
$clauses[] = "MSTCITY = " . $db->quote($city);
}
if ($bdrms != null){
$clauses[] = "MSTBDRMS >= " . $bdrms;
}
if ($bths != null){
$clauses[] = "MSTBATHS >= " . $bths;
}
if ($lprice != null){
$clauses[] = "MSTLISTPRC BETWEEN " . $lprice . " AND " . $hprice;
}
$query .= implode(" AND ", $clauses) . ";";
$db->setQuery($query);
$table = $db->loadRowList();
return $table;
I ended up getting rid of nameQuote and quote except where needed/applicable. The script model I was working off of was from some tutorial. It worked for what I was doing previously, but not now for some reason. Last step would be to make the initial AND conditional, but that shouldn't take much. At least the framework is there now. Thanks to all who helped.
I've made this php code for filtering the results from a mysql database. It works very well, but I'm sure this is not the most efficient way (or proper use of the language) to achieve the desired results. I'm trying my best to get "good" at writing code and would appreciate some feedback on how I could do this better.
$filter = "";
if (isset($_POST['submit']))
{
$aircraft_reg = "";
$prefix = "";
$part_number = "";
$flight_control = "";
if(!empty($_POST['aircraft_reg']))
{
$aircraft_reg = "aircraft_reg = '" . $_POST['aircraft_reg'] . "'";
}
if(!empty($_POST['prefix']))
{
$prefix = "prefix = '" . $_POST['prefix'] . "'";
}
if(!empty($_POST['part_number']))
{
$part_number = "part_number = '" . $_POST['part_number'] . "'";
}
if(!empty($_POST['flight_control']))
{
$flight_control = "flight_control = '" . $_POST['flight_control'] . "'";
}
if ($aircraft_reg != "" && ($prefix != "" || $part_number != "" || $flight_control != ""))
{
$a = " AND ";
}
else
{
$a = "";
}
if ($prefix != "" && ($part_number != "" || $flight_control != ""))
{
$b = " AND ";
}
else
{
$b = "";
}
if ($part_number != "" && $flight_control != "")
{
$c = " AND ";
}
else
{
$c = "";
}
if ($aircraft_reg != "" || $prefix != "" || $part_number != "" || $flight_control != "")
{
$filter = "WHERE " . $aircraft_reg . $a . $prefix . $b . $part_number . $c . $flight_control;
}
}
$result = mysql_query("SELECT * FROM installed $filter ORDER BY aircraft_reg , part_number, date_installed ASC");
You only need follow this pattern:
$result = mysql_query("
SELECT *
FROM installed
WHERE
".($_POST['aircraft_reg']?"aircraft_reg=" .mysql_real_escape_string($_POST['aircraft_reg']):"1" )." AND
...
ORDER BY aircraft_reg , part_number, date_installed ASC");
another alternative:
foreach($_POST as $key => $val)
if($key!="submit" and $val)
$filters[] = "$key='".mysql_real_escape_string($val)."' ";
$result = mysql_query("
SELECT *
FROM installed
".(isset($filters)?"WHERE ".implode("AND ",$filters):"")."
ORDER BY aircraft_reg , part_number, date_installed ASC");
I suggest you using something well-established such as ActiveRecord:
http://www.phpactiverecord.org/
No need to re-invent the wheel (unless this is purely for learning, in which case, carry on!)
... in the case this is purely for learning, don't forget to escape any REQUEST data such as those $_POSTs that you're using, with something like mysql_real_escape_string
Quick:
Use array_key_exists to see if something is in $_POST
Do not put $_POST values directly in your SQL, escape them. More info when you Google for SQL injection attack
I would validate/sanitize your input first, and then create the query in one go:
if (array_key_exists("partnumber", $_POST) {
$part_number = validate_partnumber($_POST['partnumber']);
$part_number = escape_for_db($part_number);
}
$q = ".... WHERE part_number='$part_number' ....";
Other than that, it doesn't look too bad.
You can try this, as conditional operator has less time complexity than if()-else(). Moreover less use of variables will cause less memory allocation, hence it is faster and more optimized than the one you used.
Another thing, using mysql_real_escape_string() prevent sql injection.
$filter = "";
if (isset($_POST['submit']))
{
$condition_count = 0;
if(!empty($_POST['aircraft_reg']))
{
$filter = " WHERE aircraft_reg = '" . mysql_real_escape_string($_POST['aircraft_reg']) . "'";
$condition_count++;
}
if(!empty($_POST['prefix']))
{
$condition_count > 0?$filter .= " AND prefix = '" . mysql_real_escape_string($_POST['prefix']) . "'":$filter .= " WHERE prefix = '" . mysql_real_escape_string($_POST['prefix']) . "'";
$condition_count++;
}
if(!empty($_POST['part_number']))
{
$condition_count > 0?$filter .= " AND part_number = '" . mysql_real_escape_string($_POST['part_number']) . "'":$filter .= " WHERE part_number = '" . mysql_real_escape_string($_POST['part_number']) . "'";
$condition_count++;
}
if(!empty($_POST['flight_control']))
{
$condition_count > 0?$filter .= " AND flight_control = '" . mysql_real_escape_string($_POST['flight_control']) . "'":$filter .= " WHERE flight_control = '" . mysql_real_escape_string($_POST['flight_control']) . "'";
$condition_count++;
}
}
$result = mysql_query("SELECT * FROM installed ".$filter." ORDER BY aircraft_reg , part_number, date_installed ASC");
if (!isset($_POST['submit'])) exit;
$aircraft_reg = $_POST['aircraft_reg'];
$prefix = $_POST['prefix'];
$part_number = $_POST['part_number'];
$flight_control = $_POST['flight_control'];
$result = mysql_query("
SELECT *
FROM installed
where
aircraft_reg = if('$aircraft_reg' = '', aircraft_reg, '$aircraft_reg')
and
prefix = if('$prefix' = '', prefix, '$prefix')
and
part_number = if('$part_number' = '', part_number, '$part_number')
and
flight_control = if('$flight_control' = '', flight_control, '$flight_control')
ORDER BY aircraft_reg , part_number, date_installed
");
If this is for real then don't forget to sanitize the user input or you will be an easy sql injection victim.
I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant