Getting multiple data from database (or so) - php

I'm trying to get multiple bookings from my database for a hotel project
when i tried to get the bookings from my database i only recieved one booking it should display/select multiple bookings.
This is my php code:
(formulier.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) { include_once 'source.php';
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
And this is my other php code: (source.php)
<?php
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
}
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}
?>
this is my database: (dt_tb)
https://gyazo.com/966efdf144a8cd1a74fa04a8127cd8f4
This is what i receive: (Website)
https://gyazo.com/1384bdafb5055f5777a40e88baccdbdd
I know my code is messed up badly and tried to solve it for quite some time.

I don't know why you need two files. You can join them to single loop.
<?php
$dt1 = !empty($_POST['date1']) ? $_POST['date1'] : null;
$dt2 = !empty($_POST['date2']) ? $_POST['date2'] : null;
if (!$dt1 || !$dt2) {
throw new Exception("No dates passed!");
}
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "check-in: {$row['dt']}<br/>";
echo "check-out: {$row['dt2']}<br/>";
echo "<br/>";
}
} else {
echo "No bookings found between {$dt1} and {$dt2}";
die();
}
?>
What was wrong:
require_once is called only for first iteration, no further calls was made. It's used mostly when including classes or some configs, that must be included only once in whole logic.
You try to echo your data outside loop inside source.php
You echo passed parameters to server, but not actual database record entries. Changed $dt1 to $row['dt'] and $dt2 to $row['dt2']

You repeated the query in both files! Why?
As you typed, you don't need to include 2 lines! , you can add them directly:
$dt1 = $_POST['date1'];
$dt2 = $_POST['date2'];
$query = "SELECT * FROM dt_tb WHERE dt BETWEEN '$dt1' AND '$dt2'";
$result = mysqli_query($connect,$query);
if (mysqli_num_rows($result)) {
while($row = $result->fetch_assoc()) {
echo "source.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
echo "<br>formulier.php";
echo "<br>check-in: $dt1 <br>check-out: $dt2";
}
else {
die;
}

Related

How to combine SQL query with a PHP script

I have this query to count the number of forms that are submitted by a certain user
$sql="SELECT `ID` FROM `kform` WHERE `ID`='$ID'";
$result = $conn->query($sql);
$k=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$k++;
}
}
plus I have this php script that is basically check a certain date (which is included in each form) and prints valid if it is within this fiscal year
$endYear = 2017;
while($endYear <= 2025) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y')) -> add(new DateInterval('P1D'));
$ddb = $row2['Date'];
$dateFromDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFromDB >= $initDate && $dateFromDB <= $endDate) {
echo "valid\n";
echo "\tStartDate->\"".$initDate->format("Y-m-d")."\"\n";
echo "\tEndDate->\"".$endDate->format("Y-m-d")."\"\n";
echo "\tDateFromDatabase->\"".$dateFromDB->format("Y-m-d")."\"\n";
}
$endYear++;
}
Now what I was trying to do is to combine these two functions together, the idea behind that is to count only the forms that are in this fiscal year, any older forms should not be counted. I tried different ways to combine them but it gave me different errors every time, So is it even possible to do so?
Go on from that:
function isValidYear($dategiven){
$endYear=2017;
while($endYear<=2025) {
$end = $endYear.'/06/30';
$endDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = DateTime::createFromFormat('Y/m/d', $end);
$initDate = $initDate->sub(new DateInterval('P1Y'))->add(new DateInterval('P1D'));
$ddb = $dategiven;
$dateFromDB = DateTime::createFromFormat('Y-m-d', $ddb);
if ($dateFromDB>=$initDate && $dateFromDB<=$endDate) {
return true;
}
$endYear++;
}
return false;
}
And
$sql="SELECT `ID` FROM `kform` WHERE `ID`='$ID'";
$result = $conn->query($sql);
$k=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if(isValidYear($row['datefield'])){
$k++;
}
}
Note: Your $sql selects only the ID field. You have to at Date
$sql="SELECT * FROM `kform` WHERE `ID`='$ID'";

Fatal error: Call to undefined method mysqli_result::format()

I know that the error says that format isn't a valid code, but I used it before and it worked fine. So I hope someone knows a code to replace it with or now how to fix it.
require_once 'config.php';
$checker = "SELECT StartTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker2 = "SELECT EndTime FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$checker3 = "SELECT Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result1 = mysqli_query($mysqli, $checker);
$result2 = mysqli_query($mysqli, $checker2);
$minutes = mysqli_query($mysqli, $checker3);
$starttime = new DateTime($result1);
$endtime = new DateTime($result2);
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";
and above I grab the vars out of the database
The problem is mysqli_query returns a mysqli_result which you need to read before using:
require_once 'config.php';
$checker = "SELECT StartTime, EndTime, Minutes FROM ap21_Teachers WHERE Mentor_Class = 'I2C'";
$result = mysqli_query($mysqli, $checker); //Execute query
if (!$result) { //Result may be false if there's an error
echo "Error getting result";
}
$row = mysqli_fetch_assoc($result); //Put first result in an array
if (!$row) { // $row will be false if there's no result
echo "No data found";
}
//Notice how the array entry keys match the columns in the query.
$starttime = new DateTime($row["StartTime"]);
$endtime = new DateTime($row["EndTime"]);
$minutes = $row["Minutes"];
while($starttime <= $endtime)
{
echo "<option value='".$starttime->format('H:i:s')."'>".$starttime->format('H:i:s')."</option>";
$starttime = date_add($starttime, date_interval_create_from_date_string($minutes, ' min'));
}
echo " </select>";

Insert date check into function

I have this function that loads an array from a table called 'customer' it works fine, but I also want it to check if the customer has expired and if so display an error
So I have code below that to check if the id_expiry_date is over, but I'm having difficulty working out where to put it in the function. Tried a few things, but just seems to break. Please assist.
function customer_load_by_id($id)
{
$dbh = dbh_get();
$id = array();
$sql = 'select c.* ' .
'from customer c ' .
'where c.cust_id = (select max(cust_id) from customer where id = ?)';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($id));
$r = $stmt->fetch();
if (!is_bool($r)) {
$fields = id_get_fields();
foreach ($fields as $field) {
$n = $field['name'];
$id[$n] = $r[$n];
}
}
dbh_free($dbh);
$exp_date = "$id_expiry_date";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
//continue happily
} else
{
//don't continue
}
return $id;
}
// One of the fields in the array above is id_expiry_date
I do not really get how you SQL schema is but, using Pomm, I would write the following code:
<?php
use PommProject\Foundation\Pomm;
$loader = require __DIR__ . '/vendor/autoload.php'; //<- setup autoloading
$pomm = new Pomm(…); // <- connection params go there
$sql = <<<"SQL"
select
c.*,
c.expiry_date < now() as is_expired
from customer c
where c.cust_id = (select max(cust_id) from customer where id = $*)
SQL;
$result = $pomm
->getDefaultSession()
->getQueryManager()
->query($sql, [$id])
->current() // <- Take the first row if exist
;
if ($result) {
if ($result['is_expired']) { //<- 'is_expired' is converted as boolean
echo "expired";
} else {
echo "not expired";
}
} else {
echo "no result";
}

PHP SQL loop outputs as 0 rows

I am trying to create a PHP loop to show the players the tournaments they are partaking in. I tried the function on phpMyAdmin, and I got the result that I wanted. But when I try to run this simple script on PHP, it outputs as 0 rows.
index.php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if($mybb->user['uid']) {
$sql = "SELECT * FROM players, tourneys WHERE players.forumname = 1 AND players.tid = tourneys.id";
$result = mysqli_query($conn, $sql);
// output data of each row
if (mysqli_num_rows($result) > 0) {
// output data of each ro
while($row = mysqli_fetch_assoc($result)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo $name;
echo $date;
echo $time;
}
} else {
echo "0 rows";
}
}
The problem is not in "if ($mybb->user['uid']) {" as suggested by #Dagon. Try to leave the well indented code to avoid this kind of confusion. Run the code below and post the the DB error output.
Try this:
<?php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if ($mybb->user['uid']) {
$player_forumname = '1';
// Return only the necessary fields
$sql = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$player_forumname}";
$result = mysqli_query($conn, $sql);
// If the query fails display the error
if ($result === FALSE) {
die('MySQLi Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) == 0) {
die('0 rows');
}
// Returns only the associative array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo 'Name:',$row['name'],'Date:',$row['date'],'Time:',$row['time'];
}
}

for each if true fetch mysqli result

Hello i try to print all results from a table where time is in futre:
thank you for any help or tips.
<?php
function show_entrys($all){
$connectSQL = mysqli_connect("localhost", "root", "Timur", "eventdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach ($all as $one){
$Eid = $one['event_id'];
$Tid = $one['time_id'];
$dtA = $one['endtime'];
$dtB = date('Y-m-d H:i:s');
$date1 = strtotime("7 February 2008");
$date2 = strtotime("8 February 2008");
actually i'd like to check with $dtB and $dtA:
SQL QUERY QUESRION:
can i make a innerjoin query with the following query? : "select starttime, endtime from time where id = $ "
if not i will solve this in anotherway. here comes the query:
if($date2 > $date1){
$sql = $connectSQL->query("SELECT name, description, genre_id, photo FROM eventWHER id=$Eid");
here i want to fetch every entry in the table into an array
}
else {
echo" no events in the future ";
}
}
while($row= mysqli_fetch_array($sql,MYSQLI_ASSOC)){
$events[] = $row;
}
foreach ($events as $one){
echo $one['name'];
echo $one['description'];
echo $one['genre_id'];
echo $one['photo'];
}
mysqli_close($connectSQL);
}
everything works except that i use the while in the div.
You need to parse MySQL results inside If statement. Otherwise, you will only have the last run of foreach ($all as $one).
Then, the query is FROM event WHERE id=$Eid, instead of FROM eventWHER id=$Eid.
<?php
function show_entrys($all){
$connectSQL = mysqli_connect("localhost", "root", "Timur", "eventdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach ($all as $one){
$Eid = $one['event_id'];
$dtA = $one['endtime'];
$dtB = date('Y-m-d H:i:s');
$date1 = strtotime("7 February 2008");
$date2 = strtotime("8 February 2008");
if($date2 > $date1){
$sql = $connectSQL->query("SELECT name, description, genre_id, photo FROM event WHERE id=$Eid");
while($row= mysqli_fetch_array($sql,MYSQLI_ASSOC)){
$events[] = $row;
}
foreach ($events as $one){
echo $one['name'];
echo $one['description'];
echo $one['genre_id'];
echo $one['photo'];
}
}
}
else
echo" no events in the future ";
}
mysqli_close($connectSQL);

Categories