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.
Related
I am having a huge issue looping through results, These two queries work hand in hand to check if a restaurant is open today. My problem is i have restaurants, id 1-5(more in the future). But the loop seems to only get restaurant id 5. I have read many posts on here and it seems like i am doing the right thing. But i cannot seem to loop to get the other restaurant id's.
I am blocked now, newbie who is very open to any suggestions or advise.
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++;
}
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
You could either output whatever you want to within your loop or build-up an output string because the value of $rest_ will always be the last value in the loop and i don't think that's what you want... Again you are doing the same with $message. And I am willing to bet that this is what you want to do:
<?php
date_default_timezone_set("Europe/London");
$sel = "SELECT Rest_Details.Resturant_ID,Delivery_Pcode.Pcode,Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID=Rest_Details.Resturant_ID
WHERE Delivery_Pcode.Pcode LIKE'$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
$i=1;
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
$i++; // <== YOU DON'T NEED THIS VARIABLE....
// GET THE DATES WITHIN THE LOOP...
$daynum = jddayofweek(unixtojd());
$query = "SELECT *
FROM Opening_hrs WHERE
Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "</br>";
}
} else {
$message = $message . "close" . $row_qu["Closing_time"] . "</br>";
}
}
I think this is what you are trying to do.
// $searchP should be checked to prevent SQL injection.
$sel = "SELECT Rest_Details.Resturant_ID, Delivery_Pcode.Pcode,
Delivery_Pcode.Restaurant_ID
FROM Rest_Details INNER JOIN Delivery_Pcode
ON Delivery_Pcode.Restaurant_ID = Rest_Details.Resturant_IDW
WHERE Delivery_Pcode.Pcode LIKE '$searchP'";
$res = $dbc->query($sel);
if (!$res) {
echo "invalid query '" . mysqli_error($dbc) . "\n";
}
// set these once as they don't change
date_default_timezone_set("Europe/London");
$daynum = jddayofweek(unixtojd());
// $i=1; - not required, never used
// loop over the original results
while ($row_res = $res->fetch_array()) {
$rest_ = $row_res['Resturant_ID'];
//$i++; not used
// check for a match
$query = "SELECT * FROM Opening_hrs
WHERE Restaurant_ID = $rest_
AND Day_of_week = $daynum";
$run_qu = $dbc->query($query);
if ($run_qu->num_rows > 0) {
// at least one match
while ($row_qu = $run_qu->fetch_assoc()) {
$message = "open" . $row_qu["Open_time"] . "<br />";
$message .= "close" . $row_qu["Closing_time"] . "<br />";
}
} else {
// no matches
$message = "No results for <i>$daynum</i>.";
}
}
It should be possible to get the details in a single query, but I would need to see your SQL tables for that (and you did not ask for that too :]).
Also, it is <br> or <br />, not </br>.
I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.
I'm not sure why this SQL query is not working.
I'm new to SQL/PHP so please forgive.
mysql_query("
SELECT * FROM table WHERE name = " . "'Bob'" .
while($i < $size)
{
$i++;
echo "OR name = '";
echo $array[$i] . "'";
} .
" ORDER BY id DESC "
);
Dreamweaver gives me an error saying it is not correct but does not tell me what is wrong.
Is it possible to put a while loop into an sql command?
you can not use a while in a string
$where = "";
if ($size > 0)
{
$where .= " WHERE ";
}
while($i < $size)
{
$i++;
$where .= "OR name = '".$array[$i]."' ";
}
$query = "SELECT * FROM table WHERE name = '".Bob."'".$where." ORDER BY id DESC";
mysql_query($query);
(this code is not tested)
Woot !
You just can't write this :D
Build your OR condition before writing the query and it will be just fine:
$myCondition = " ";
while($i < $size) {
$i++;
$myCondition .= "OR name = '" . $array[$i] . "'";
}
mysql_query(
"SELECT * FROM table WHERE name = " . "'Bob'" . $myCondition . " ORDER BY id DESC ");
echo is to output the string, and it won't return the string.
Something like $str = "aaa" . echo "bbb"; won't work.
For you case, use IN will be better.
foreach ($array as &$name) {
$name = "'".mysql_real_escape_string($name)."'";
}
mysql_query("SELECT * FROM table WHERE name IN (".implode(',', $array).")");
Or use
"SELECT * FROM table WHERE name IN(".implode( ',', $array).")";
I tried combining as suggested in a previous link but Im still getting a error. I am fairly new to php so that is why i have two querys.
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/vhockey/public_html/vhatest/connect.php on line 88
The table is "season12" and the table is "p"
Here is my connect.php file except server info...
function index_team_stats($subconference) {
$return = array();
$query = "SELECT id, teamname, teamnameseason, teamabr
FROM teams
WHERE subconference = '" . $subconference . "'
ORDER BY teamnameseason";
$teams = result_array($query);
foreach ($teams as $team)
{
$query = "SELECT gp, w, l, ol, p
FROM season12
WHERE team = '" . $team['teamnameseason'] . "'
ORDER BY p DESC
LIMIT 0,20'; ";
$results = result_array($query);
if ($results)
{
$results[0]['team'] = str_replace($team['teamnameseason'], '', $team['teamname']);
$results[0]['teamabr'] = $team['teamabr'];
$results[0]['teamid'] = $team['id'];
$return[] = $results[0];
}
}
return $return;
}
function get_team_name($teamnameseason) {
$query = "SELECT teamname FROM teams WHERE teamnameseason = '" . $teamnameseason . "'";
$row = mysql_fetch_row(mysql_query($query));
return str_replace($teamnameseason, '', $row[0]);
}
function result_array($query) {
$results = mysql_query($query) or die("error on: " . $query . " saying: " . mysql_error());
$return = array();
while ($row = mysql_fetch_assoc($results)) {
$return[] = $row;
}
return $return;
}
Here is an image of the info ![All info sorted by team PTS from highest to lowest
Should show Penguins, FLyers, Islanders, Rangers, Devils..
Use a JOIN. An example is below. You may need to tweak based on your specific needs.
SELECT teams.id, teams.teamname, teams.teamnameseason, teams.teamabr, season12.gp,
season12.w, season12.l, season12.ol, season12.p
FROM teams, season12
INNER JOIN season12
ON teams.teamname=season12.team
WHERE teams.subconference = '$subconference'
ORDER BY season12.p
LIMIT 0,20
Please note this code is not tested and may require modification.
You can use php sort function http://php.net/usort
$callback = new function ($el1, $el2) {
if ($el1['points'] == $el2['points']) {
return 0;
}
return ($el1['points'] < $el2['points']) ? -1 : 1;
}
$sorted_result = usort($results, $callback);
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