Displaying date from mysql in php - php

So i want to get one and only the first value from a date column in my database, and put it in my PHP file, this is the snippet of the code to get the date:
$one = 1;
$Lihat="SELECT * FROM event where status = '$one'";
$Tampil = mysqli_query($db, $Lihat);
while ( $hasil = mysqli_fetch_array ($Tampil)) {
$query_start_date = "SELECT tgl_event
FROM jadwal_acara
WHERE id_event = '$id_event' AND status = $one
ORDER BY tgl_event ASC
LIMIT 1";
$result = mysqli_query($db, $query_start_date);
$start_date = mysqli_fetch_field($result);
<td class="tgl_mulai"><?php echo date('d-m-Y', strtotime($start_date));?></td>
The problem is that when i tried to echo it in my table row:
It returns an error that said:
strtotime() expects parameter 1 to be string, object given.
Does anyone know how to change it into a string or another method to get the desired display result? Thank you.
EDIT:
$start_date = var_dump($start_date); returns a NULL value when i tested it.
Notice: Undefined property: stdClass::$tgl_event in
NULL
But i got other rows that displayed the correct name and event ID, it's just the date that won't display correctly.
it now displays :01-01-1970

mysqli_fetch_field() returns an object. Instead use mysqli_fetch_assoc
Try this:
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT tgl_event FROM jadwal_acara WHERE id_event = ".$id_event." AND status = 1 ORDER BY tgl_event ASC LIMIT 1";
if ($result = mysqli_query($db, $query)) {
while ($finfo = mysqli_fetch_assoc($result)) {
$date = date('m-d-Y', strtotime($finfo['tgl_event']));
}
mysqli_free_result($result);
}
mysqli_close($db);
And then in your HTML:
<td class="tgl_mulai"><?php echo $date; ?></td>

Related

Error getting result from second query using variables from first query

I get result from first query correctly However, when I want to use them in second query in WHERE condition I get query error 1064. If I remove WHERE it will work fine. Also,when I try to echo variables inside while in second query code it will print.the variables will not work only in WHERE in second query
$queryDate = "SELECT date , time from DATES where ID = $ID";
$result = mysqli_query($connection, $queryDate);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$date = $row['date'];
$time = $row['time'];
}
}
$queryCom = "SELECT * from DATES, BOOKING where dates.time = $time and booking.IDofFullDate= $date";
$result1 = mysqli_query($connection, $queryCom);
if (!$result1)
{
die("Query Faile". mysqli_errno($connection));
}
if ($result1->num_rows >0) {
echo $date;
echo $time;
}
on your second query try this below:
$queryCom = "SELECT * from DATES as dates, BOOKING as booking where dates.time = $time and booking.IDofFullDate= $date";

Getting each item which is available in a certain period out of database

I want to echo each car ID which is available in a period between the start_date and the end_date. So far i got this with some help here on SO. This gives me a page not responding, if I delete the second part (commented in the script down here) it is eching all the car id's but not only the ones which are available ofcourse. What is wrong with the script? Because i cant figure out what i did wrong here.
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$items = array();
$result = mysqli_query($con, "SELECT * FROM invoice_line ");
while ($car = mysqli_fetch_array($result)) {
echo $car['car_car_id'];
//second part
$car_available = mysqli_query($con, "SELECT *
FROM invoice_line
WHERE car_car_id = $car['car_car_id']
and start_date>='$start_date'
and end_date<='$end_date'");
echo $car_available['car_car_id'];
} // end second part
?>
The process you are doing is:
1. fetch all lines from invoice_line
2. for each line, fetch all lines between two dates.
You do it wrong, because you do not have to use two queries. You can use one:
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$result = mysqli_query($con, "SELECT car_car_id FROM invoice_line where start_date>='$start_date' AND end_date<='$end_date'");
while ($car = mysqli_fetch_array($result)) {
echo $car['car_car_id'];
} // end second part
?>
I would add distinct for car_car_id, in order to get only one line per car id. if you want other data frome this line, you have to add it in the "SELECT" query
Will you try this code? Hope it may solve your problem you're echoing $car['car_car_id'] twice in your code but you missed the loop of your available cars
<?php
$start_date = '2017-06-12';
$end_date = '2017-06-14';
$items = array();
$result = mysqli_query($con, "SELECT * FROM invoice_line ");
$carid = null;
while ($car = mysqli_fetch_array($result)) {
$carid = $car['car_car_id'];
echo $carid;
//second part
$car = mysqli_query($con, "SELECT * FROM invoice_line WHERE car_car_id = '$carid' AND start_date>='$start_date' AND end_date<='$end_date'");
while ($car_available = mysqli_fetch_array($car)) {
echo $car_available['car_car_id'];
}
} // end second part
?>

get prior row from a mysqi query in php

I have a view in MySQL called published_people that looks like this:
PersonID Name LastName MarkerID date
-------- ---- -------- -------- ----
1198 Jane Doe Doe 1174 2015-05-20
864 John Doe Doe 863 2015-04-23
1187 Richard Roe Roe 1165 2015-05-21
1190 Sam Spade Spade 1167 2015-01-01
I have a post variable representing the marker ID of the person whose page of data I'm viewing.
I have another post variable that represents the last name of the person whose page of data I'm viewing.
I want to be able to iterate through published_people. If the LastName field matches the variable, I want to get the prior record (the one before this one) in published_people.
Here's my code in php so far:
include_once ('constants_test.php');
$mysqli_prior = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit();
}
//get the year I'm looking for
$this_date = mysqli_real_escape_string($mysqli_prior, $_POST['this_date']);
$pieces = explode("-", $this_date);
$this_year = $pieces[0];
//find the last name of the person I'm looking for
$marker_id = $_POST['marker_id'];
$q_getLastName = "select LastName from published_people where MarkerID =" . $marker_id;
$result = mysqli_query($mysqli_prior,$q_getLastName);
$r = $result->fetch_row();
$thisLastName = $r[0];
//get all records from this year, alphabetized by last name
$q = "select * from published_homicides where year(date) = '" . $this_year . "' order by LastName";
$result = $mysqli_prior->query($q);
$allresults = array();
$num_rows = mysqli_num_rows($result);
if ($num_rows != 0) {
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
// How do I say this?
// if $row["LastName"] == $thisLastName then find the record
// PRIOR TO this one and do the following:
$results = array($row['Name'], $row['date']);
array_push($allresults, $results);
}
echo json_encode($allresults);
} else {
echo "nothing";
}
mysqli_close($mysqli_prior);
I ended up creating a variable to hold the data from the previous record. I iterated through the query. When the MarkerID equaled the marker_id of the record I wanted the previous one of, I stopped:
$priorname = ""; //initialize at nothing
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
$results = array($priorname);
array_push($allresults, $results);
} else {
$priorname = $row['Name']; //save this data in $priorname
}
}
echo json_encode($allresults);
mysqli_close($mysqli_prior);
So that was getting the prior record.
I also wanted to get the next record.
I handled this problem in two parts. First I went through my query, counting the row I was on. When my post variable called marker_id matched the MarkerID in the database view, I stopped the query:
$marker_id = $_POST['marker_id'];
$q = "select MarkerID, Name, LastName, date from published_people order by year(date) desc, LastName asc";
$result = $mysqli_next->query($q);
$allresults = array();
$count = 0;
//we'll go through the list of names in alphabetical order by year
while($row = $result->fetch_array(MYSQLI_BOTH)) {
$count++; //keep track of what row you're on
//compare the row id to the posted id
if ($row['MarkerID'] == $marker_id) {
//if they're the same, stop this query - we have counted to the spot that they matched
break;
}
}
Now I know where to set a limit on another query:
//make a new query with a limit of one record starting at the row # indicated by $count
$newq = "select MarkerID, Name, LastName, date from published_homicides order by year(date) desc, LastName asc LIMIT " . $count . ",1";
$result2 = $mysqli_next->query($newq);
while($row2 = $result2->fetch_array(MYSQLI_ASSOC)) {
$results = array($row2["Name"]);
array_push($allresults, $results);
}
echo json_encode($allresults);
mysqli_close($mysqli_next);

Whats wrong with the syntax in my mysql select statement (php, mysql)

I have a table and i'm trying to extract the maximum value of a column called order_num, which has 33 intries of integers 1 through 33. I want the value "33" in this instance as its the highest number.
$userid is an integer derived from a one row table with a field id that I am trying to retrieve
//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
$result_array[] = $row['id'];
}
//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;
Doing a print_r on $userId shows the array to be empty, that's why the code below doesn't work.. :(
...
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
$result_array[] = $row['MAX(order_num)'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
}
The output I get is
the result is the result is the result is
Does anyone know why i'm not able to get the result from the table?
Edit:
Okay, try this:
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
print_r($row);
}
What do you get?
Your first code to get the userId doesn't work because of your usage of the array, change to:
$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
$userId = $row['id'];
}
As I've shown below, if you only expect a single row then remove the while loop and just call fetch_assoc a single time.
Given you only want the single row you don't need the while loop:
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
$row = mysqli_fetch_assoc($reOrderDeckResult);
echo 'result: ' . $row['order_num'];
}
else
{
echo 'No rows found!!';
}
I also added LIMIT 1 to the query, and a check to see if there are any rows.
You have renamed your MAX(order_num) AS order_num so you should try to get value using order_num only as echo $result_array['order_num']
and in while you should check whether you are getting value or not by placing below code in while loop
echo '<PRE>';
print_r($row);
echo '</PRE>';
This may helps you..,
<?php
$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));
$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {
//you have to use the alias name not aggregate function title
$result_array[] = $row['order_num'];
echo "the result is" . $result_array['order_num'];
echo "the result is" . $row['order_num'];
//you have to use the alias name not aggregate function title
echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}

PHP, resource id# instead of actual string

I have run across a problem during my query service to add a row in an online database in PHP. The addition of the row works just fine. I get user id and book id from the url and fetch the names of the book and the user to put into the row which i add to my third and last table.
When I get the names, put them in an array, json encode it and then echo it, it works. But when I put them in the row it prints resource id#3 and resource id#4 instead of the names.
Any ideas?
Here is my service:
<?php
$con = mysql_connect("localhost","root","root");
$userid=$_GET['uid'];
$id = $_GET['bookid'];
$type = $_GET['type'];
$zero = '0';
$one = '1';
$date = date("Y-m-d");
$arr = array();
if (!$con)
{
die('Could not connect: ' . mysql_error());
echo "error connection";
}
mysql_select_db("Jineel_lib",$con) or die("Could not select database");
$bkName = mysql_query("SELECT Name from books where ID='".$id."'");
$userName = mysql_query("SELECT Name from people WHERE User_ID='".$userid."'");
while($obj = mysql_fetch_object($userName))
{
$arr[] = $obj;
}
echo json_encode($arr);
if($type == 'borrow')
{
$query="UPDATE books set Availablity = '".$zero."' where ID= '".$id."' ";
mysql_query($query) or die (" borrow operation failed due to query 1");
$query1="INSERT into borrowed (BookID, BookName, BorrowerID, BorrowedName, DateBorrowed, Extended, Returned) values('".$id."','".$bkName."','".$userid."','".$userName."','".$date."','".$zer‌​o."','".$zero."')";
mysql_query($query1) or die (" borrow operation failed to due query 2");
echo "borrow success";
}
else if($type=='return')
{
$query="UPDATE books set Availablity = '".$one."' where ID= '".$id."' ";
mysql_query($query) or die (" return operation failed");
$query1="UPDATE borrowed set Returned = '".$one."' where BookID= '".$id."' ";
mysql_query($query1) or die (" return operation failed 1");
echo "return success";
}
else
echo "invalid parameters";
?>
THANK YOU IN ADVANCE
You don't actually retrieve the userName value here:
$userName = mysql_query("SELECT Name...
$userName is just the result resource object returned from the query. You do use mysql_fetch_object later on, which is appropriate, but then you try to use the actual result resource in your insert query:
$query1="INSERT into borrowed ...
It gets converted to the string you see. Instead, you need to use $obj->Name (you fetch the result into $obj, and presumably there is only one result). If there is more than one possible result, you will have to do that in a loop.
Listen to all of the comments on your question.

Categories