MySQL INNER JOIN with date as condition - php

I'm trying to use inner join to get the data from two tables using date as one of the condition. But since the second table contain dateTime column type, I want to use only the date to check for condition. When i run the code using Postman, it says I have error in SQL syntax at line (DATE)checkInDateTime = $rideDate . I also have test the SQL without taking the date into condition and the SQL works . Is there any ways to use the date as condition in InnerJoin method? Please help me . Thanks.
P/s : my dateTime column store values such as 2015-01-08 11:18:02
//get all rides from table rides
$result = mysql_query("SELECT first.ID, first.fullname,
second.checkInDateTime FROM first INNER JOIN second ON first.ID =
second.riderID WHERE second.ridesID = $rideID AND second.
CAST(checkInDateTime AS DATE) = $rideDate") or die(mysql_error());
//check for empty result
if(mysql_num_rows($result) > 0) {
//loop all result and put into array riders
$response["riders"] = array();
while ($row = mysql_fetch_array($result)) {
//temp array
$rider = array();
$rider["riderID"] = $row["ID"];
$rider["riderName"] = $row["fullname"];
$rider["timeCheckedIn"] = $row["checkInDateTime"];
//push single ride into final response array
array_push($response["riders"], $rider);
}
//success
$response["success"] = 1;
//print JSON response
echo json_encode($response);
} else {
//no rides found
$response["success"] = 0;
$response["message"] = "No riders found";
//print JSON response
echo json_encode($response);
}

I'm guessing the (DATE)checkInDateTime is an attempt at typecasting, and you're getting the sql error because that's not the right syntax... try CAST(checkInDateTime AS DATE) instead.

Related

Data is not Found from Database in PHP

Today or Current Date Birthday Date Retrieve From the Ms Access Database.Suppose Today Date is 03-08-2018. I passed value only Date and Month day = 03, Month = 08 and year is not Pass. So, I Retrieve Current day and month record.
Data Retrieve Query in PHP File.This Query Run in Ms Access database is Successfully and fetch current date Record but In PHP file Give Empty Data.
Passed data in url just Like this: localhost/Bi.php?Chhaprabhatha&mon=8&day=3
Its Give Result Like This: Resource id #4{"status":0,"0":[]}
Query is Run in Database its give Result and Successfully run.In this code give null data
Bi.php
<?php
if(isset($_REQUEST["Chhaprabhatha"]))
{
include 'Connection.php';
$mon = $_GET['mon'];
$day = $_GET['day'];
$sql = "select std_name, regno,standard,division
FROM(select RegNo,b.Standard,c.Division,std_name,DOB as BirthDayDate,contactno1 as contact, Year(DOB) AS OrderYear, month(DOB) AS OrderMonth,Day(DOB) AS OrderDay,a.YearID,IsActive
from ((std_reg as a inner join standardmaster as b on a.standard = b.stdid)
inner join divisionmaster as c on a.division = c.divisionid)
) as t where (t.OrderMonth = $mon AND t.OrderDay = $day and t.Isactive = true)";
echo $stmt = odbc_exec($conn, $sql);
$result = [];
do {
while ($row = odbc_fetch_array($stmt)){
$result[] = $row;
}
} while (odbc_next_result($stmt));
if(count($result)>0)
{
$result1['status']=1;//"Login successfully";
echo array_push($result1,$result);
}
else
{
//$result[]="null";
$result1['status']=0;//"Record not found";
array_push($result1,$result);
}
odbc_free_result($stmt);
odbc_close($conn); //Close the connnectiokn first
echo json_encode($result1); //You will get the encoded array variable
}
?>

Loop a variable inside an sql query

I'm trying to work out the following,
I am querying a Salesforce db with PHP, an seems that they don't really allow relationship queries, which is my whole problem, so need to run 2 queries, a query first to populate a variable that is used into a second query right after.
That variable will hold a string with usernames, just plain text usernames, that I need to match with an Id that will match a OwnerId after,
something like this,
<?php
$query = "SELECT FirstName FROM User WHERE Id in (SELECT OwnerId from Case WHERE Region__c = 'WORLD' and CaseOwnerManager__c = 'some_guy' AND Status = 'Open')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
for ($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
$firstName = $record->fields->FirstName;
echo $firstName."<br>\n";
}
$query = "SELECT CaseNumber, Status FROM Case where Status = 'Open' and OwnerId in (SELECT Id FROM User where FirstName = '{$firstName}')";
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
for($queryResult->rewind(); $queryResult->pointer < $queryResult->size; $queryResult->next()) {
$record = $queryResult->current();
$caseNumber = $record->fields->CaseNumber;
$status = $record->fields->Status;
echo $caseNumber."<br>\n";
echo $status."<br>\n";
}?>
Of course, in the above, the second query, the one with the $firstName variable, it picks up the last value of the string and then the loop gives the CaseNumber and Status of that single user.
So what i need to do is get that second query in some sort of loop and while it is looping, get the $firstName variable to loop as well.
So at the end, $firstName should populate the th of a table and $caseNumber and $status its tds
Any ideas on how to do it, or if it even can be done?
Cheers.

Creating json from sql query with an additional key/value pair using PHP

Disclaimer: I'm fairly new to php.
I am trying to create an array out of a query witch could return multiple results. Additionally, I am doing a distance calculation and adding that value to the array, creating a json string, then returning it to my javascript.
I can create the array with the data from the database, and insert the additional value into the array, and return it, but when I try with a query witch returns more than one result, I'm only getting the last result back, because the array is being over written. I've tried to the array_merge function, but I'm still only getting the last one back.
Here is what I have so far:
$positionquery = "select d.code, d.lon, d.lat from table1 as d where d.lon <> 0 and d.lat <> 0 and d.brand = 'THE_BRAND'";
$results = mysql_query($positionquery) or die ('Query Failed" ' . mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results)){
$locations = $row;
$tempdistance = distance($lat, $lon, $locations['lat'], $locations['lon'], 'M');
if($tempdistance <= 150){
$secondquery = 'SELECT * FROM table1 as d left join table2 as p on p.dealer_name = d.dealer_name left join table3 as o on o.retailercode = d.cicode where d.cicode ="'.$locations['cicode'].'"';
$queryResults = mysql_query($secondquery) or die('Query Failed ' . mysql_error());
$tempArray = mysql_fetch_assoc($queryResults);
$tempArray['distance'] = $tempdistance;
$returnArray = array_merge($returnArray,$tempArray);
}
}
echo json_encode($returnArray);
}
Any help would be greatly appreciated.
You're not creating an array of results, you're overwriting the $returnArray variable with each row of the results. It should be:
$returnArray = array();
while ($row = mysql_fetch_assoc($results)) {
...
$returnArray[] = $tempArray;
}
echo json_encode($returnArray);

Select row of information for each array element

I have this bit of code that doesn't produce anything, not even an error message. I'm trying to echo the result inside the while loop, but even that doesn't show anything. Any tips?
foreach($droppedStudentIds as $value){
$query3 = "select * from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists)";
if($result = mysqli_query($mysqli, $query3)) {
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "Date: ".$row['ClassListDate'];
$droppedStudentIds[$value][] = $row['ClassListDate'];
}
mysqli_free_result($result);
} else die ("Could not execute query 3");
}
My goal is to look up a date information for each element inside the $droppedStudentIds array. I checked the MySQL query in itself and it produces that desired result.
Thanks!
You're assigning to the array you're looping through on this line:
$droppedStudentIds[$value][] = $row['ClassListDate'];
This could be causing your script to timeout, which would be why you're not seeing any output.
I'd add a second array to avoid conflicts and use that for storing results from the query, e.g.
$temp[$value] = $row['ClassListDate'];
Thanks all for the response, it helped pin down the mistake!
No need for a while loop when asking for a single record
The query was actually incorrect. The subselect was getting the maximum date in the database, regardless of whether the StudentId was present or not. The correct query is the following:
select ClassListDate from student_classlists where StudentId = '$value' and ClassListDate = (select max(ClassListDate) from student_classlists where StudentId = '$value')
Thanks again!

Couldn't get data from another table in MySQL

I am currently trying to get a data(M_Name) from a table called Merchant.
Following are my codes:
<?php
$response = array();
$link = mysql_connect('localhost','root','') or die ('Could not connect: '.mysql_error());
mysql_select_db('ichop') or die ('Could not connect to database');
$result = mysql_query("select * from offer") or die(mysql_error());
if(mysql_num_rows($result) > 0){
$response["offers"] = array();
while($row = mysql_fetch_array($result)){
$offer = array();
$offer["offer_id"] = $row["Offer_ID"];
$offer["start_date"] = $row["Start_Date"];
$offer["end_date"] = $row["End_Date"];
$offer["o_desc"] = $row["O_Desc"];
$offer["short_desc"] = $row["Short_Desc"];
$offer["merchant_ID"] = $row["Merchant_ID"];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
array_push($response["offers"], $offer);
}
$response["success"] = 1;
echo json_encode($response);
} else {
//no offer found
$response["success"] = 0;
$response["message"] = "No offer found";
echo json_encode($response);
}
?>
When I run this PHP file using web browser, I couldn't get the desired name for the merchant even though the data is there in the database...it would just return me "null".
{"offers":[{"offer_id":"1","start_date":"2013-05-17","end_date":"2013-05-18","o_desc":"AAA","merchant_ID":"2","m_name":null}],"success":1}
What have I done wrong or what am I still missing? Please help..thanks!
I would rather use LEFT JOIN mysql function and get all relevant data at first query from both of your tables
SELECT * FROM offer a LEFT JOIN MERCHANT b ON a.Merchant_ID = b.MERCHANT_ID
so you won't have to make any extra query and you can store your value directly in your array
$offer["m_name"] = $row['M_Name'];
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO
The mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"); does not return a value from the DB, you need to follow it up with for example mysql_fetch_array like you did with the other query to the DB.
There is a solution more simple: use a JOIN, which combines two tables.
SELECT offer.*, MERCHANT.M_Name
FROM offer
LEFT JOIN MERCHANT ON(MERCHANT.MERCHANT_ID = offer.merchant_ID)
look like you have to return an result from query instead of while,
mysql_fetch_array(mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"));
but had better you make some error hadling first
You can use below one
$resMerchant = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
$rowMerchant = mysql_fetch_assoc($resMerchant);
$offer["m_name"] = $rowMerchant['M_Name'];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'")
mysql_query() does not return a string but a resource. You'll have to fetch the result.
Also, don't forget that mysql_* is now deprecated.
[edit]
As stated by Fabio, you'd rather use JOIN on your query. At the moment, you are making a request in your loop. That's useless (INNER JOIN or LEFT JOIN are what you want) and very resource consumming.

Categories