Hi still a beginner in php programming and one of the function of my project is to check if the schedule exist or not in the database. anyway my problem is that the way i created the string query, i am not sure if the string is correct in terms of syntax but the query is correct and tested in the phpmyadmin MySQL GUI.
$start_time = $_POST['Time-In'];
$end_time = $_POST['Time-Out'];
$procedure_date = $_POST['txbDateofProcedure'];
$DateStartTime = $procedure_date." ".$start_time;
$DateEndTime = $procedure_date." ".$end_time;
//Not sure but i think that the $Check-Schedule php syntax is incorrect
$Check_Schedule = "select * from appointment_dim where dentist_id = '$dentist_id'".
"and (CONCAT(appoint_date, ,appoint_timein) between '$DateStartTime' and '$DateEndTime')".
"OR (CONCAT(appoint_date, ,appoint_timeout) between '$DateStartTime' and '$DateEndTime')";
$result_schedule = mysql_query($Check_Schedule,$con);
if(!$result_schedule)
{
trigger_error("Cannot located database".mysql_error());
die();
}
if(mysql_num_rows($result_schedule) > 0)
{
$SchedErrMesg = "The time you requested is already take try again.";
echo"<script type='text/javascript'>alert('$SchedErrMesg');</script>";
die();
}
if you want the delimiter between appoint_date and appoint_time* to be space, you should do this:
CONCAT(appoint_date, ' ', appoint_timein)
but not this:
CONCAT(appoint_date, , appoint_timein)
Also i believe u want the logic like
"dentist_id = x AND (timeBetween1 OR timeBetween2)"
But not that u wrote:
"(dentist_id = x AND timeBetween1) OR timeBetween2"
So try this:
$Check_Schedule = "
SELECT * FROM appointment_dim
WHERE
dentist_id = '$dentist_id'
AND (
(CONCAT(appoint_date, ' ', appoint_timein) BETWEEN '$DateStartTime' AND '$DateEndTime')
OR (CONCAT(appoint_date, ' ', appoint_timeout) BETWEEN '$DateStartTime' AND '$DateEndTime')
)
";
Related
I have a web application and I'm trying to modify one of the queries. The query fetches information (from a table named voyage_list) and returns various fields.
I want to modify the query so that it is based on certain filters the user applies (which will be placed in the URL).
I can't get the query to work in the web application, but if I copy the query and execute it directly within PHPMyAdmin, it works fine.
$vesselFilter = $_GET['vesselFilter'];
$vesselArray = explode(',', $vesselFilter);
$arrayCount = count($vesselArray);
$sqlExtend = ' status = 1 AND';
foreach ($vesselArray as $value) {
$i = $i + 1;
$sqlExtend .= " vesselID = '$value'";
if ($i < $arrayCount){
$sqlExtend .= " OR";
}
}
$newQuery = "SELECT * FROM voyage_list WHERE" . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
I appreciate the above is pretty messy, but it's just so I can try and figure out how to get the query to work.
Any help would be greatly appreciated!
Thanks
That query probably doesn't return what you think it does. AND takes precedence over OR, so it will return the first vessel in the list if the status is 1, and also any other vessel in the list, regardless of status.
You'd do better to create a query with an IN clause like this:
SELECT * FROM voyage_list WHERE status = 1 AND vesselID IN(8,9,10)
Here's some code to do just that:
$vesselFilter = $_GET['vesselFilter'];
// Validate data. Since we're expecting a string containing only integers and commas, reject anything else
// This throws out bad data and also protects against SQL injection.
if (preg_match('/[^0-9,]/', $vesselFilter)) {
echo "Bad data in input";
exit;
}
// filter out any empty entries.
$vesselArray = array_filter(explode(',', $vesselFilter));
// Now create the WHERE clause using IN
$sqlExtend = 'status = 1 AND vesselID IN ('.join(',', $vesselArray).')';
$newQuery = "SELECT * FROM voyage_list WHERE " . $sqlExtend;
echo $newQuery;
$query = $db->query($newQuery)->fetchAll();
var_dump($query);
My code checks if there is $GET value, if not then assign ALL values of array.
Seems like simple thing,not sure why its not working.
if(isset($_GET["smonth"])) {$smonth= $_GET["smonth"];
}
else {$smonth =12;} working , but not what I want
else {$smonth =array (1,2,3,4,5,6,7,8,9,10,11) ;}
After that I would like to use it in SQL :
and d.month_of_year = '".$smonth."%'
That would be something like
and month_of_year = (all values of array) or 1 value)
My Question:
What would be best solution to check, if active month is available? If not, assign All months to query.Thank You
The built-in PHP functions of in_array and implode should solve your issue:
in_array('1', $_GET["smonth"]); // checks if January is in $_GET["smonth"]
implode("," , $_GET["smonth"]); // Pull all of the values out of $_GET["smonth"] as a A STRING
Try in your statement and d.month_of_year IN (" . implode(',', $smonth) . ")
= operator checks for single value. If you want to check multiple values, use in.
and d.month_of_year in (".$smonth.")
You also have a % there, which works with LIKE queries.
<?php
if(isset($_GET['month'])){
$month = date('m'); //This would give you the index of the current month.
$array = array('01','02','02');
$query = "select * from table where month = ";
if(in_array($month,$array)){
$query = "select * from table where month = '".$month."'";
//Then query here
}
else
{
$query = "select * from table";
$where = "";
foreach($month as $m){
$where .= ' month = "'.$m.'" and ';
}
//There would be a ending and pls just try remove it
$query .= $where;
// then query here
}
}
?>
I haven't been writing PHP/SQL in a few years and needed to do this for a project. And now I have run into a problem.
I wanting to grab some data from a MySQL databas, between specific dates. It works just fine if write it like this:
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' and added between '2012-11-05' and '2012-11-10' ");
But I want to get the dates from the URL, and have written this:
$periods = $_GET["per"];
if ( $periods == 1 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
elseif ( $periods == 2 ) {
$period = "and added between '2012-11-11' and '2012-11-17'";
}
elseif ( $periods == 3 ) {
$period = "and added between '2012-11-05' and '2012-11-10'";
}
echo $period;
If I echo $period I got the correct output in the HTML but when trying to insert it to my MySQL questions i got nothing, what does I do wrong?
$result = mysql_query("SELECT * FROM acw WHERE team = '".$team."' '".$period."' ");
So something is wrong with this, and can't solve it by my self :(
Your string in $period is a full chunk of SQL, not a quoted string literal. So remove the single quotes surrounding it.
$result = mysql_query("SELECT * FROM acw WHERE team = '". $team ."' " . $period);
//---------------No quotes here----------------------------------------^^^^^^^^^^
Note: We assume that $team, if originating from user input, has already been properly escaped against SQL injection via mysql_real_escape_string()
It is recommended to always debug your SQL statement by echo'ing out the string. It would have been a little more obvious to see a string like:
SELECT * FROM acw WHERE team = 'The Team' 'and added between '2012-11-05' and '2012-11-10''
A final word of advice - unless this is already done in code not posted here, verify that $_GET['per'] is set before attempting to use it:
// Set $periods to the $_GET value or defualt to 1 if it isn't set (or whatever value)
$periods = isset($_GET["per"]) ? $_GET['per'] : 1;
ok so I've been trying for a while now to get this to work but there has to be a better solution than what im thinking about. I'm fairly new to php/mysql so not sure how to do the following:
I have a search box that contains dropdowns for country, state, city
Now if the user only selects country and clicks on search it needs to filter the select by just country and show everything else.
if(!empty($_REQUEST['city']))
$city = $_REQUEST['city'];
else
$city= "%";
if(!empty($_REQUEST['state']))
$state= $_REQUEST['state'];
else
$state= "%";
if(!empty($_REQUEST['country']))
$country= $_REQUEST['country'];
select * from table where country = $country and state = $state and city = $city
problem with this is that those columns are ints so I can't use the "%" to filter it. I hope I was able to explain it any help is more than welcome. Thanks in advance
If you don't want to constrain a column, simply omit it from your query
never insert a string from $_REQUEST directly into a query string -- classic SQL injection flaw.
you probably want to enforce some sort of limit, lest the query return every single result in your database.
example:
<?php
$conditions = array();
if(!empty($_REQUEST['city']))
$conditions[] = "city = " . mysql_real_escape_string($_REQUEST['city']);
if(!empty($_REQUEST['state']))
$conditions[] = "state = " . mysql_real_escape_string($_REQUEST['state']);
if(!empty($_REQUEST['country']))
$conditions[] = "country = " . mysql_real_escape_string($_REQUEST['country']);
$sql = 'select * from table ';
if(!empty($conditions))
$sql .= ' where '. implode(' AND ', $conditions);
$sql .= ' LIMIT 1000';
$where = array();
if(!empty($_REQUEST['city'])) $where[] = "city = '".(int)$_REQUEST['city']."'";
if(!empty($_REQUEST['state'])) $where[] = "state = '".(int)$_REQUEST['state']."'";
if(!empty($_REQUEST['country'])) $where[] = "country = '".(int)$_REQUEST['country']."'";
$wherestring = if(count($where) != 0) ? " WHERE ".implode(' AND ', $where) : "" ;
$query = "SELECT * FROM table".$wherestring;
You may want to consider writing several query strings, one for just country, one for state and country and one for city, state and country. Alternatively you can assemble the query string based upon the different parameters you have to work with.
Example:
if(isset() || isset() || isset() ) //make sure at least one is set
{
$query_string = "SELECT * FROM table WHERE ";
if(isset($_REQUEST['country']))
{
$country = $_REQUEST['country'];
$query_string .= " country = $country";
}
if(isset($_REQUEST['state']))
{
$state = $_REQUEST['state'];
$query_string .= " state = $state";
}
if(isset($_REQUEST['city']))
{
$city = $_REQUEST['city'];
$query_string .= " city = $city";
}
}
else
{
//Else, if none are set, just select all the entries if no specifications were made
$query_string = "SELECT * FROM table";
}
//Then run your query...
So in english, the first thing you do is check your parameters, making sure you have something to work with before you try and concatenate empty variables together.
Then you make the base query string (as long as we have parameters) and leave it open ended so that we can add whatever parameters you need.
Next check each parameter, and if it is set, then concatenate that parameter onto the end of the query string.
Finally process the query by sending it to the SQL server.
Good luck!
h
Here're my suggestions.
I'm giving you an answer, even though you have three already. I'm thinking mine may be easier on the code-eyes.
Do not use the raw $_REQUEST value, as it's likely that the user can poison your database by feeding it fake $_REQUEST data. Though there may be better ways to do it, keep in mind the command "mysql_real_escape_string($string)".
A common method I've seen for solving this problem is written below. (The implode idea, basically. Frank Farmer does it as well in his.)
-
$__searchWheres = array(); //Where we'll store each requirement used later
foreach( array('city','state','country') as $_searchOption) {
if ( ! empty( $_REQUEST[$_searchOption] ) ) {
$__searchWheres[] = $_searchOption . '= "' . mysql_real_escape_string( $_REQUEST[$_searchOption] ) . '"';
}
}
$__query = 'select * from table' . (count($__searchWheres) > 0 ? ' WHERE ' . implode(' AND ',$__searchWheres) : ''); //Implode idea also used by Frank Farmer
//Select from the table, but only add the 'WHERE' key and where data if we have it.
mysql_query($__query);
Ok, i have a problem here...
I am sending values of drop down lists via ajax to this PHP file.
Now I want to search a mysql database using these values, which I have managed to do, BUT, only if I set the values to something...
Take a look:
$query = "SELECT * FROM cars_db WHERE price BETWEEN '$cars_price_from' AND '$cars_price_to' AND year BETWEEN '$cars_year_from' AND '$cars_year_to' AND mileage BETWEEN '$cars_mileage_from' AND '$cars_mileage_to' AND gearbox = '$cars_gearbox' AND fuel = '$cars_fuel'";
now, what if the user doesnt select any "price_from" or "year_from"... The fields are only optional, so if the user doesnt enter any "price from" or "year from", then the user wants ALL cars to show...
Do I have to write a query statement for each case or is there another way?
I do something similar to davethegr8 except I put my conditions in an array and then implode at the end just so I don't have to worry about which conditions got added and whether I need to add extra AND's.
For example:
$sql = "SELECT * FROM car_db";
// an array to hold the conditions
$conditions = array();
// for price
if ($car_price_from > 0 && $car_price_to > $car_price_from) {
$conditions[] = "(price BETWEEN '$cars_price_from' AND '$cars_price_to')";
}
elseif ($car_price_from > 0) {
$conditions[] = "(price >= '$cars_price_from')";
}
elseif ($car_price_to > 0) {
$conditions[] = "(price <= '$cars_price_from')";
}
else {
//nothing
}
// similar for the other variables, building up the $conditions array.
// now append to the existing $sql
if (count($conditions) > 0){
$sql .= 'WHERE ' . implode(' AND ', $conditions);
}
You could simply detect which parameters are missing in your PHP code and fill in a suitable default. eg
if (!isset($cars_mileage_to))
$cars_mileage_to = 500000;
You can build you query, adding the "where" part only if your variables are different from "".
or if you're using mysql 5.x, you can also use subselects:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
don't forget to validate the input. It's trivial with firebug, for example, to inject some tasty sql.