Hi there i am using a sqlite database to manage reservations on a system (written in php and html) that I built. I have managed to connect to the database and run a simple count query that runs (see code below). However i am finding it difficult to execute a query that will allow me to select reservations between two dates i.e (2018-02-20 and 2018-02-25). I have also enclosed a screenshot of my database for visualization purposes.
Code for count query:
<?php
$db = new PDO('sqlite:daypilot.sqlite');
$query = 'SELECT count(*) FROM events;';
$result = $db->query($query);
$data = $result->fetch(PDO::FETCH_ASSOC);
echo "There are {$data['count(*)']} bookings made\n";
?>
Since you'll be passing input to your query, you'll want to use a prepared statement rather than just query(). It looks like your events table has two dates, so the following query should catch all events that overlap a specified date range.
$start = '2018-02-20';
$end = '2018-02-25';
$sql = 'SELECT * FROM events WHERE `end` > ? AND `start` < ?';
$stmt = $db->prepare($sql);
$stmt->execute([$start, $end]);
$events = $stmt->fetchAll();
foreach ($events as $event) {
var_dump($event); // output with your desired formatting here
}
Related
I am trying to build an SQL query that will insert the check-in time for a child at a fictional daycare facility. Here is a condensed version of my query code:
$childFirstName = $_POST['childFirstName'];
$childLastName = $_POST['childLastName'];
$now = new DateTime();
$nowDate = $now->format('m-d-Y');
$nowTime = $now->format('h:i');
$sql_childID = "SELECT id FROM child
WHERE firstName = '$childFirstName'
AND lastName = '$childLastName'";
$result = $pdo->query($sql_childID);
$row = $result->fetch();
$sql = "INSERT INTO checkinout(date, in, child_id) VALUES(?,?,?)";
$statement = $pdo->prepare($sql);
$statement->bindValue(1, $nowDate);
$statement->bindValue(2, $nowTime);
$statement->bindValue(3, $row['id']);
$statement->execute();
The checkinout table uses VARCHAR datatypes for the date and in columns. Originally they were set to use DATETIME, but I received the same errors.
Right now I get the following errors returned...
You can see from the error messages that my values are getting passed in the way I want them to, but I don't understand where my syntax error would be.
Enclose your field names with backticks. Two of them are reserved words (date and in):
$sql = "INSERT INTO checkinout(`date`, `in`, `child_id`) VALUES(?,?,?)";
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
I am so sorry mybe it is a silly question but as I am new in web language and php I dont know how to solve this problem.
I have a code which is getting ID from user and then connecting to MySQL and get data of that ID number from database table and then show on webpage.
But I would like to what should I add to this code if user enter an ID which is not in table of database shows a message that no data found.
Here is my code:
<?php
//connect to the server
$connect = mysql_connect ("localhost","Test","Test") ;
//connection to the database
mysql_select_db ("Test") ;
//query the database
$ID = $_GET['Textbox'];
$query = mysql_query (" SELECT * FROM track WHERE Code = ('$ID') ");
//fetch the results / convert results into an array
$ID = $_GET['Textbox'];
WHILE($rows = mysql_fetch_array($query)) :
$ID = 'ID';
echo "<p style=\"font-color: #ff0000;\"> $ID </p>";
endwhile;
?>
Thank You.
Sorry if it is so silly question.
You should use PDO (great tutorial here: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers ). This way, you can develop safer applications easier. You need to prepare the ID before inserting it to the query string, to avoid any user manipulation of the mysql query (it is called sql injection, guide: http://www.w3schools.com/sql/sql_injection.asp ).
The main answer to your question, after getting the results, you check if there is any row in the result, if you got no result, then there is no such an ID in the database. If you use PDO statements $stmt->rowCount();.
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM table WHERE Code=?");
$stmt->bindValue(1, $id, PDO::PARAM_INT); // or PDO::PARAM_STR
$stmt->execute();
$row_count = $stmt->rowCount();
if ($row_count > 0) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//results are in $results
} else {
// no result, no such an ID, return the error to the user here.
}
Another reason to not use mysql_* functions: http://php.net/manual/en/migration55.deprecated.php
I am using PHP PDO to retrieve objects to an iOS app via JSON.
There is a database table with event objects. It has three fields to store day, month and year. The owner of the database doesn't want to store dates in a date field, that means that I have to deal with it.
The app sends a URL with params,like this:
http://..hidden domain./myfile.php?dia_inicio=16&dia_final=15&mes_inicio=11&mes_final=12&ano_inicio=2014&ano_final=2015
That means that I am looking for events from 16Nov2014 to 15Dec2015.
This is my PHP code:
$sql = 'SELECT * FROM tbagenda WHERE (dia_evento => :di AND mes_evento = :mi AND ano_evento = :ai) OR (dia_evento <= :df AND mes_evento = :mf AND ano_evento = :af) ';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
$stmt->bindParam(':di', $dia_inicio, PDO::PARAM_INT);
$stmt->bindParam(':df', $dia_final, PDO::PARAM_INT);
$stmt->bindParam(':mi', $mes_inicio, PDO::PARAM_INT);
$stmt->bindParam(':mf', $mes_final, PDO::PARAM_INT);
$stmt->bindParam(':ai', $ano_inicio, PDO::PARAM_INT);
$stmt->bindParam(':af', $ano_final, PDO::PARAM_INT);
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// convert to json
$json = json_encode( $result );
// echo the json string
echo $json
How should I change my statement to make it work with dates like: 16Nov2014 to 28Nov2014 (same month), 16Nov2014 to 5Dec2014 (different month, same year) and 16Nov2014 to 02May2015(different year)?
ADDED LATER:
iOS log to show the URL send to the PHP file:
recuperar_eventos_dia.php?dia_inicio=11&dia_final=26&mes_inicio=11&mes_final=11&ano_inicio=2014&ano_final=2014
PHP part:
$start = "$ano_inicio-$mes_inicio-$dia_inicio";
$end = "$ano_final-$mes_final-$dia_final";
// In the SQL, concatenate the columns to make a YYYY-MM-DD date string
// and cast it to a MySQL DATE type.
// That makes it possible to use BETWEEN
$sql = 'SELECT
*
FROM tbagenda
WHERE STR_TO_DATE(CONCAT_WS('-', ano_evento, mes_evento, dia_evento), "%Y-%m-%d")
BETWEEN :start AND :end';
// Bind and execute the statement with 2 parameters:
$stmt = $dbh->prepare( $sql );
$stmt->bindParam(':start', $start, PDO::PARAM_STR);
$stmt->bindParam(':end', $end, PDO::PARAM_STR);
$stmt->execute();
// fetch, etc...
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// convert to json
$json = json_encode( $result );
// echo the json string
echo $json;
And now a screenshot from the table tbagenda:
I'm sorry that you're stuck with this unfortunate table structure.
I would suggest concatenating the table's columns to form usable date strings, and cast them to a date value via MySQL's built in function STR_TO_DATE(). Do the same with your query string input values to make proper date comparisons with a BETWEEN operator.
// Begin by concatenating the input values into single date strings YYYY-MM-DD
$start = "$ano_inicio-$mes_inicio-$dia_inicio";
$end = "$ano_final-$mes_final-$dia_final";
// In the SQL, concatenate the columns to make a YYYY-MM-DD date string
// and cast it to a MySQL DATE type.
// That makes it possible to use BETWEEN
$sql = "SELECT *
FROM tbagenda
WHERE STR_TO_DATE(CONCAT_WS('-', ano_evento, mes_evento, dia_evento), '%Y-%m-%d')
BETWEEN :start AND :end";
// Bind and execute the statement with 2 parameters:
$stmt = $dbh->prepare( $sql );
$stmt->bindParam(':start', $start, PDO::PARAM_STR);
$stmt->bindParam(':end', $end, PDO::PARAM_STR);
$stmt->execute();
// fetch, etc...
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
The string operations will affect performance of this query. It would be better, as you know, if the dates were stored as a proper DATE so MySQL would not need to cast them for comparisons. They could also then be indexed.
Note also that I did not include validation of the date strings. You might consider checking them to be sure they make valid dates before executing the query.
// strtotime() would return false for invalid date strings...
if (strtotime($start) && strtotime($end)) {
// The dates are valid, and so you can proceed with the query
$sql = 'SELECT.....';
}
i am having a bit of issue with a mysql query. for some reason i can echo all all associated rows inside of the mysql query but outside of the query it only return the last row. here is my code. any suggestions?
//Get all associated
$q=mysql_query("SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'");
while ($row = mysql_fetch_assoc($q)){
$act_name=$row['ACT_NAME'];
echo "$act_name<br>"; // This returns all rows fine
}
echo "$act_name<br>"; // This only return the last row. i would like to get all rows.
The only way that you can fetch all of the records is by using PDO or MySQLi. Here is an example:
$conn = new mysqli($hostname, $username, $password, $database);
$query = "SELECT * FROM `ACCOUNT` WHERE ACCOUNT_ID='$act_id'";
$results = $conn->query($query);
$resultArray = $results->fetch_all(MYSQLI_ASSOC);
As #esqew said, you need to stop using the mysql_* functions.
Right, so i'm still getting my head around prepared statements and every time i think, yeah i've got it, a new query comes along and i'm thinking Hmmmm i would i set that up?
So here we go, i have a query that pulls records from a database based on a date and orders them by said date. The records it finds are based on a year and month value and the query looks like this:
$getresults = mysql_query(" SELECT * FROM `results` WHERE `date` LIKE '2012-$monthid%' ORDER BY date ");
I already have basic prepared statement for getting a users record from my database:
$query = "SELECT *
FROM results
WHERE date = ?
LIMIT 1";
if($stmt = $this->conn->prepare($query))
{
$stmt->bind_param('s', $date);
$stmt->execute();
if($stmt->fetch())
{
$stmt->close();
return true;
}
else
return false;
}
How would i change this to make it more like the first query?
Thanks for the help.
One idea would be to filter by year and month in separate parts of the WHERE clause:
$query = "SELECT * FROM results WHERE YEAR(date) = 2012 AND MONTH(date) = ? ORDER BY date";
if ($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('i', $monthid);
...
}