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);
Related
I am new to php and struggling to get the data from a table in mysql and using it to connect to an ftp server. The table contains the external ip address of the ftp server, the base directory to change into and login credentials to use. I fetched the data from mysql and stored it in an array but while looping through it I get
php notice: trying to access array offset on type null.
Code:
$now = time();
$yesterday = $now - (24 * 60 * 60);
$date = date("Y-m-d", $yesterday);
if (isset($_GET['date'])) {
$date = $_GET['date'];
}
$startDate = "$date 00:00:00";
$endDate = "$date 23:59:59";
//$conn = &newEtConn();
$sql= "SELECT stager_usr, stager_pwd, stager_ip, basedir, view_direction from et_devices.cameras as a inner join et_params.stagers as b on a.stagerid = b.idstagers ";
$result = mysqli_query($conn,$sql);
$datas = array();
if (!$result) {
die ("table Connection problem");
}
if (mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)){
$datas[] = $row;
}
print_r($datas);
}
if ($row!= "") {
foreach ($datas as $values) {
$ip_addr = $values['stager_ip'];
$login = $values['stager_usr'];
$password = $values['stager_pwd'];
$basedir = $values['basedir'];
if ($rows != "") {
$gotFtpConn = True;
$ftp_obj = ftp_connect($ip_addr, 21, 10) or $gotFtpConn = False;
if ($gotFtpConn) {
if (ftp_login($ftp_obj, $login, $passwd)) {
echo "could not connect" . $login;
return false;
}
return $newEtConn;
}
}
}
There are a few things that I don't like (and can improve)...
It looks like you intend to filter your database data based on a date, but then you never actually apply that value to the array. I'll help to clean up that process.
Your if ($row != '') check after the loop will always fail because the loop ONLY stops when $row becomes falsey.
The rest of your code looks like it only intends to process a single row in the result set (because it returns). I am going to assume that you have more conditional logic in your query's WHERE clause which ensures that only one row is returned -- otherwise, you shouldn't be using return in your loop.
$date = !empty($_GET['date']) && preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['date'])
? $_GET['date']
: date('Y-m-d', strtotime('yesterday'));
$sql = "SELECT stager_usr, stager_pwd, stager_ip
FROM et_devices.cameras AS a
JOIN et_params.stagers AS b ON a.stagerid = b.idstagers
WHERE DATE(a.some_datetime_column) = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $date);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
$ftp = ftp_connect($row['stager_ip'], 21, 10);
if (!$ftp) {
throw new Exception('Failed to establish FTP connection');
}
if (!ftp_login($ftp, $row['stager_usr'], $row['stager_pwd'])) {
throw new Exception('Incorrect FTP login credentials');
}
return $ftp;
}
throw new Exception('FTP connection data not found');
If you experience a noticeable performance bottleneck with DATE() in your sql, then there are other techniques that may be faster, but they use longer/uglier syntax.
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;
}
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>";
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";
}
Here I am trying to get some data from database and want to display it as a json response so that user can fetch each field.
Here is how user can perform query
http://localhost/safari/index.php?getbranch=true
this should give branch details from tables.
Here is PHP code to do it
<?php
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division, branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1 = json_encode($row);
}
echo $result1;
}
What's wrong wit this?
JSON response:
[{"0":"3","sno":"3","1":"2","division":"2","2":"2","branch":"2","3":"SAFFARI TRAVELS","branchofficename":"SAFFARI TRAVELS","4":"gfgbhghfhf","branchofficecode":"gfgbhghfhf","5":"active","status":"active"},
{"0":"4","sno":"4","1":"2","division":"2","2":"chennai","branch":"chennai","3":"chennai","branchofficename":"chennai","4":"br01","branchofficecode":"br01","5":"active","status":"active"},{"0":"5","sno":"5","1":"3","division":"3","2":"delhi","branch":"delhi","3":"delhi","branchofficename":"delhi","4":"br02","branchofficecode":"br02","5":"notactive","status":"notactive"},{"0":"6","sno":"6","1":"2","division":"2","2":"bangalore","branch":"bangalore","3":"bangalore","branchofficename":"bangalore","4":"br03","branchofficecode":"br03","5":"active","status":"active"},{"0":"7","sno":"7","1":"3","division":"3","2":"pune","branch":"pune","3":"pune","branchofficename":"pune","4":"br04","branchofficecode":"br04","5":"notactive","status":"notactive"}]
Change your while loop
$result1 = array();
while ($row = #mysqli_fetch_array($result))
{
array_push($result1 , $row);
}
by doing so, you have collected all result in $result1
now you can encode it
echo $result1 = json_encode( $result1);
I will prefer to use array, ignor json_encode line code,
foreach($result1 as $resultset){
//resultset contains one single row of table
foreach($resultset as $column => $columnValue){
//assuming your table column name as 'city'
if($column == 'city' && $columnValue == 'pune' ){
//displaying array of table which satisfies the condition
var_dump($resultset );
}
}
}
$result1 = array();
if(isset($_GET['getbranch']))
{
$getbranch = $_GET['getbranch'];
if($getbranch == 'true')
{
getbranch($getbranch);
}
}
function getbranch($getbranch)
{
$con = mysqli_connect('127.0.0.1', 'root', '', 'safari');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$today = date("Ymd");
$result = mysqli_query($con,"SELECT division,
branch,branchofficename,branchofficecode,status from tbl_branchoffice");
while ($row = #mysqli_fetch_array($result))
{
$result1[] = $row;
}
echo json_encode($result1);
}
First collect each row from the result into the array result1 and then finally output the json_encode of $result1 array