PHP and MySQL query - multiple criteria - php

I'm having a problem with the code listed below where I'm running a query on a database based on search criteria the user may have selected on a form.
At the moment, querying the database just on the author's name works fine. But if I uncomment the rest of the if-else statements, none of the queries work. I just get a blank table back with no results returned.
I've tried each if/else statement individually with the others commented out and they all work fine on their own, but not when they're all uncommented.
Can anyone point me in the right direction?
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if ($_POST['author'])
$query .= " AND '$author' = author";
/*
else if ($_POST['author'] AND $_POST['year'])
$query .= " AND '$author' = author AND '$year' = year";
*/
/*
else if ($_POST['cover_art']) {
$query .= " AND '$cover_art' = cover_art";
}
*/
/*
else if ($_POST['interior_art']) {
$query .= " AND '$cover_art' = cover_art";
}
else {
// do something else
}
*/

Check this solution:
$author='Bred';
$year='2012';
$cover_art='';
$queryA=array();
if ($author<>'') $queryA []= "'$author' = author";
if ($year<>'') $queryA []= "'$year' = year";
if ($cover_art<>'') $queryA []= "'$cover_art' = cover_art";
$query = "SELECT * FROM books WHERE book_no IS NOT NULL";
if(count($queryA)>0) $query.=' AND '.implode(' AND ',$queryA);
echo $query;

Related

php and mysql updating row not count update as duplicate

My code is big and I can't just pull out few lines to show my problem so I am going to explain it by using imaginary code to simplify it.
Let's say I have to-do list as table and I've defined activity and time. I don't want to have duplicate rows so I created function to prevent it.
function check_date($day, $time) {
include 'db_connect.php';
$sql = "SELECT day, dan FROM todo ";
$sql .= "WHERE day = $day AND time = '{$time}'";
$result = mysqli_query($conn, $sql) or trigger_error(mysqli_error());
if(mysqli_num_rows($result) >= 1) {
$row = mysqli_fetch_assoc($result);
return 1;
} else {
return 0;
}
}
Call on function in main file:
if(check_termin_sala($day, $time)) {
$errors['busy'] = "You are busy.";
}
And query:
if(empty($errors) {
$query = "INSERT INTO todo (";
$query .= "day, time, activity";
$query .= ") VALUES (";
$query .= "'{$day}', '{$time}', '{$activity}')";
$result = mysqli_query($conn, $query);
if(!$result) {
die("Failed." . mysqli_error($conn));
}
}
Now I want update my row by changing just activity field, but fields day and time are unchanged so when I submit update I get error because exact day and time are already inserted. What should I do to exclude this check function affecting current row date and time?
I hope you will understand me. :)

Cannot figure out where to put ORDER BY

I know where not to put it, at least.
I inherited this project from my predecessor. I know very little about PHP and SQL Server, but here we are. The first while loop contains the problem. I need to ORDER BY UserType, but obviously it is just ordering one entry every time because of where it is in the while loop. The result is meant to be that the results are shown with one user type first in alphabetical order, then the second user type in alphabetical order.
Google, and searching here, have only been moderately enlightening because most examples don't seem quite this complicated. It may be something simple, but I don't see it. Any help would be appreciated.
$sql = "SELECT UserID FROM vw_AgentService WHERE StateID = ".$state.
"AND OrgID = ".$org.
"AND ServiceID = ".$service; //JOIN
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$sqlb = "SELECT * FROM vw_UserInfo WHERE UserId = ".$row["UserID"].
" AND (UserType = 1 OR UserType = 2) ORDER BY UserType DESC, UserLastName"; //Herein lies the problem
$stmtb = sqlsrv_query($conn, $sqlb);
if ($stmtb === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($rowb = sqlsrv_fetch_array($stmtb, SQLSRV_FETCH_ASSOC)) {
$sqlc = "SELECT * FROM vw_UserPhotoPath WHERE UserID = ".$row["UserID"];
$stmtc = sqlsrv_query($conn, $sqlc);
if ($stmtc === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($rowc = sqlsrv_fetch_array($stmtc, SQLSRV_FETCH_ASSOC)) {
if ($rowc['PhotoFilePath'] === null) {
echo "<a href=\"profile.php?id=".$rowb["UserID"].
"\">".
"<li><img src=\"profile/blank-avatar.png\" width=\"100\" />";
} else {
echo "<a href=\"profile.php?id=".$rowb["UserID"].
"\">".
"<li><img src=\"http://demo-bc.cmfirsttech.com:8081/".$rowc['PhotoFilePath'].
"\" width=\"100\" />";
}
}
echo $rowb["UserFirstName"].
" ".$rowb["UserLastName"].
"<br/><span class=\"info\">".$rowb["UserTitle"].
", ".$rowb["UserCompany"]; // Should the ORDER BY actually go here?
//.</span></a></li>"; //rm </br>, add ", "
}
}
I've been told that the ORDER BY usually goes at the end, but I am not sure I understand the logic because at that point it is just echoing the data I already have.
The ORDER BY clause should be added to the end of the SQL statement.
Something like this;
$sqlc = "SELECT * FROM vw_UserPhotoPath WHERE UserID = ".$row["UserID"] . " ORDER BY UserType";
That's assuming UserType is in your source view (vw_UserPhotoPath).
EDIT 1 - Should have read the question properly
You actually need your ORDER BY on the very first SQL call, ie;
$sql = "SELECT UserID FROM vw_AgentService WHERE StateID = ".$state." AND OrgID = ".$org. "AND ServiceID = ".$service . " ORDER BY UserType";
This is because the second query only returns one record. This first query is what's getting the list so where the order by should be placed.

changing table name stops the mysql query from returning row

i am returning mysql row from query . it works fine but when ever i chang the table name it stucks and returns nothing ,strange for me.
the second table is quite big with 28 feilds.
code goes here! ANY help Appreciated.
it works fine if i change table name to settings or other but when ever i change it to order it stucks.
function showorder(){
$query = "SELECT * FROM order";
if($resultset = $this->dbobj->runQuery($query)){
if ($resultset->num_rows > 0) {
$row = $resultset->fetch_assoc();
$carresult = $row;
} else {
$carresult = NULL;
$carresult .= "sorry no settings founds";
}
} else {
$carresult = die( $this->db->errno );
}
$resultset->close();
return $carresult;
}
Order is a reserved word in mysql.
if you whant to use it as a table name you have to enclose it with backticks.
$query = "SELECT * FROM `order`";

Mysql SELECT with WHERE clause not working with variable

I am pulling my hair out. I have two SELECT statements that are basically the same principal. The first one is working and the second one will not work with the WHERE clause in it. I need some fresh eyes and suggestions. I have been on every forum and read every post and have tried many "solutions" to no avail. Hoping someone will see something I have missed.
$oID = zen_db_prepare_input($_GET['oID']);
// Color coding for invoice -Start queries---
$query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
$result = $db->Execute($query);
$shiploc = $result->fields['shipping_method'];
if ($result->RecordCount() > 0) {
echo 'Test Query: = ' . $result->fields['shipping_method'];
} else {
echo 'Sorry, no record found for product number ' ;
}
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= $shiploc";
$results = $db->Execute($sql);
$newcolorblock = $results->fields['color_code'];
if ($results->RecordCount() > 0) {
echo 'Color Query: = ' . $results->fields['color_code'];
echo 'Location: = '. $results->fields['pickup_name'];
} else {
echo 'Sorry, no record found for Color Code ' ;
}
Thank you in advance for your help and suggestions hopefully you will be able to see something I can't.
First query results: Test Query: = Store Pickup (Mooresville - Gold's Gym)
Second query results: WARNING: An Error occurred, please refresh the page and try again.
If the WHERE clause is removed it returns values but not the correct ones. I need the WHERE statement for it to pull the correct information.
ANSWER kindly provided by bloodyKnuckles :)
$sql= "SELECT * FROM cart1_store_locations WHERE pickup_name= $shiploc";
changed to: (Needed to be escaped to comp for 's in the table data)
$shiploc_escaped = mysql_escape_string($shiploc);
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc_escaped."'";
I have not used this forum before. LOVE IT!!! Thank you everyone!
Since your string has a single quote in it:
Store Pickup (Mooresville - Gold's Gym)
...you need to escape the variable $shiploc:
$shiploc_escaped = addslashes($shiploc);
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc_escaped."'";
Reading up on Zen Cart Escaping Content, it appears this is an option:
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$db->prepare_input($shiploc)."'";
...and, better yet, this:
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= :pickup_name:";
$sql = $db->bindVars($sql, ':pickup_name:', $shiploc, 'string');
Your $shiploc might be null. Before second query please write var_dump($shiploc); and let us know what you get.
EDIT
$oID = zen_db_prepare_input($_GET['oID']);
// Color coding for invoice -Start queries---
$query = "SELECT * FROM cart1_orders WHERE orders_id = $oID";
$result = $db->Execute($query);
$shiploc = $result->fields['shipping_method'];
if ($result->RecordCount() > 0) {
echo 'Test Query: = ' . $result->fields['shipping_method'];
} else {
echo 'Sorry, no record found for product number ' ;
}
$sql = "SELECT * FROM cart1_store_locations WHERE pickup_name= '".$shiploc."'";
$results = $db->Execute($sql);
$newcolorblock = $results->fields['color_code'];
if ($results->RecordCount() > 0) {
echo 'Color Query: = ' . $results->fields['color_code'];
echo 'Location: = '. $results->fields['pickup_name'];
} else {
echo 'Sorry, no record found for Color Code ' ;
}

Keeping a counter

*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)

Categories