$id = 2;
// query to fetch delayed
$sql = "SELECT * FROM leads WHERE status = ('$id') LIMIT 1";
$obResult = $objConnection->query($sql);
// query to fetch if there is no delayed
$q = "SELECT * FROM leads WHERE status = ('$id') AND later != '1' ORDER BY postnummer LIMIT 1";
$oResult = $objConnection->query($q);
// primary query to run, which makes use of the two above accordingly
$query = "SELECT * FROM leads WHERE status = ('$id') LIMIT 1";
$objResult = $objConnection->query($query);
while ($row = $objResult->fetch_object()) {
if (new DateTime() > $row->delay && $row->delay != '0000-00-00 00:00:00') {
while ($row = $obResult->fetch_object()) {
echo $row->firmanavn;
}
} else {
while ($row = $oResult->fetch_object()) {
echo $row->firmanavn;
}
}
}
Changed my code to this, and still i got the same problem, the if clause if met, but it echoes from my else instead
Reason is that you are using same variable names that overwrite each other. $objResult rename this to something like $objResult2 for the inner query.
One thing to keep in mind is that your inner query inside a loop is really unnecessary unless you did not provide some piece of code. You can just put that query outside of while loop. Will save you time & memory.
Although I think there are other ways this code could be cleaned up, it seems to me that you're attempting to compare a DateTime object to a date string, which is going to yield unpredictable results. Try changing your while part to:
$current_date = new DateTime();
while ($row = $objResult->fetch_object()) {
if (
$current_date->format('Y-m-d H:i:s') > $row->delay &&
$row->delay != '0000-00-00 00:00:00'
) {
while ($row = $obResult->fetch_object()) {
echo $row->firmanavn;
}
} else {
while ($row = $oResult->fetch_object()) {
echo $row->firmanavn;
}
}
}
I'm not sure this will fully solve your issues, but it should get you closer.
Related
I was wondering how would go about executing two different queries like this:
if ($uresult->num_rows >0) {
while($urow = $uresult->fetch_assoc()) {
$rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldid' AND spaceid='$newid'");
$rresult = mysqli_query($con,"DELETE FROM allid WHERE postid AND spaceid IS NULL");
$lrow = mysqli_fetch_assoc($rresult);
$tem = $lrow['postid'];
$ujson = json_encode($tem);
echo $ujson;
}
} else {
}
I know mysqli_fetch can't hold no more than one query and there are similar questions, but I can't seem to understand the answers from the other questions. If there is a question that solves this question, I apologize and will delete this one.
all other things being equal, simple dont overwrite the $rresult from select with delete:
if ($uresult->num_rows >0) {
while($urow = $uresult->fetch_assoc()) {
$rresult = mysqli_query($con,"SELECT *
FROM allid
WHERE postid='$oldid'
AND spaceid='$newid'");
mysqli_query($con,"DELETE FROM allid
WHERE postid AND spaceid IS NULL");
$lrow = mysqli_fetch_assoc($rresult);
$tem = $lrow['postid'];
$ujson = json_encode($tem);
echo $ujson;
}
} else {
}
If you have multiple queries that either rely on a result of a previous query or need to be run in order and each successfully run, you could use transactions. With transactions if one of the queries fails, you can roll back the transaction.
First time tackling a project where i'm needing to pull data from one table (lets say 200 records/results), and based on the results of a certain column within that result set, i need to query one of my 5 other tables (which table i need to query isnt defined until i've made the first query)
I'm currently under the impression there is no way for me to use a JOIN of some kind to do this as i cannot know which table i need to join before the first set of results have come back.
so the solution i came up with was as follows (example code for simplicity sake)
$FirstTableVals = array();
$sql = ("SELECT * FROM TABLE_A");
$run = $con->query($sql);
if($run->num_rows > 0)
{
while($row = $run->fetch_assoc())
{
foreach($row as $key => $value)
{
$FirstTableVals[$key] = $value;
}
$valueToSwitch = $FirstTableVals["VAL_TO_SWITCH"];
//$SecondTable can be 1 of 5 different table names
$SecondTable = $FirstTableVals["SECOND_TABLE_TO_QUERY"];
switch ($valueToSwitch)
{
case"1":
$sql = ("SELECT * FROM $SecondTable WHERE SOME_COLUMN = SOME_VALUE");
$run = $con->query($sql);
if($run->num_rows > 0)
{
while($row = $run->fetch_assoc())
{
//save some values from the second table
}
}
//echo the results of TABLE_A and second table
break;
case"2":
$sql = ("SELECT * FROM $SecondTable WHERE SOME_OTHER_COLUMN = SOME_OTHER_VALUE");
$run = $con->query($sql);
if($run->num_rows > 0)
{
while($row = $run->fetch_assoc())
{
//save some values from the second table
}
}
//echo the results of TABLE_A and second table
break;
default:
break;
}
}
}
Now, the problem i'm running into is that once one of the "Second" sql queries is executed, after performing everything within the "Second" While loop, it will break out of the while loop its in and echo my values but stops there without breaking out of the switch statement and then running again, due to the "First" sql queries loop.
Essentially, this only seems to run for the first record inside of "TABLE_A" as opposed to looping again and executing the switch statement with "Second" sql queries for each record inside of "TABLE_A".
If any of this doesn't make any sense, please let me know and i'll do my best to elaborate on anything that may be confusing.
Really stumped with this one as it seems to me that should run as i've intended.
You are overridding the run variable, thats why it breaks the loop. Please change your code like this:
$FirstTableVals = array();
$sql = ("SELECT * FROM TABLE_A");
$run1 = $con->query($sql);
if($run1->num_rows > 0)
{
while($row = $run1->fetch_assoc())
{
foreach($row as $key => $value)
{
$FirstTableVals[$key] = $value;
}
$valueToSwitch = $FirstTableVals["VAL_TO_SWITCH"];
//$SecondTable can be 1 of 5 different table names
$SecondTable = $FirstTableVals["SECOND_TABLE_TO_QUERY"];
switch ($valueToSwitch)
{
case"1":
$sql = ("SELECT * FROM $SecondTable WHERE SOME_COLUMN = SOME_VALUE");
$run2 = $con->query($sql);
if($run2->num_rows > 0)
{
while($row = $run2->fetch_assoc())
{
//save some values from the second table
}
}
//echo the results of TABLE_A and second table
break;
case"2":
$sql = ("SELECT * FROM $SecondTable WHERE SOME_OTHER_COLUMN = SOME_OTHER_VALUE");
$run3 = $con->query($sql);
if($run3->num_rows > 0)
{
while($row = $run3->fetch_assoc())
{
//save some values from the second table
}
}
//echo the results of TABLE_A and second table
break;
default:
break;
}
}
}
I have 2 tables with a unique ID. I have a table with one of the columns being a date field. I am attempting to filter the field by today's date (which it works) from all the rows with "todays" date I want to get the cell info for #key. Once I have that ID, I want to match it with #headkey. So $headkey == $key. Once I filter that, I want to see if any of the fields match = Delivery for the ItemID column. For some reason I have an infinite loop. I played around with the logic but can't seem to get it to work. Any ideas?
$TransactionSql = "SELECT * FROM apcshead WHERE DateInvoiced > 0 ORDER BY DateInvoiced DESC";
$ItemsSql = "SELECT * FROM apcsitem";
$rs=odbc_exec($conn,$TransactionSql);
while($row = odbc_fetch_array($rs))
{
//Grabbing Transaction info
$DateInvoiced = odbc_result($rs,"DateInvoiced");
$ApcsheadKey = odbc_result($rs,"Key");
$DateInvoiced = new DateTime($DateInvoiced);
$DateInvoiced_date = $DateInvoiced->format('m-d-Y');
//$TimeStamp_time = $TimeStamp->format('h:i:s');
if ($DateInvoiced_date == $today)
{
$ItemsRs=odbc_exec($conn,$ItemsSql);
while($row = odbc_fetch_array($ItemsRs))
{
$HeadKey = odbc_result($ItemsRs,"HeadKey");
$ItemID = odbc_result($ItemsRs,"ItemID");
if ($ItemID == 'Delivery')
{
echo 'Delivery';
echo '<br />';
}
}
}
}
*UPDATE:*I modified the code again. Now what if does is it spits out 1 row with the date and then like 100 echo Delivery and then goes back and spits out another date and the same thing. Still not sure what is going on.
$TransactionSql = "SELECT * FROM apcshead WHERE DateInvoiced > 0 ORDER BY DateInvoiced DESC";
$ItemsSql = "SELECT * FROM apcsitem";
$rs=odbc_exec($conn,$TransactionSql);
while($row = odbc_fetch_array($rs))
{
$DateInvoiced = odbc_result($rs,"DateInvoiced");
$DateInvoiced = new DateTime($DateInvoiced);
$DateInvoiced_date = $DateInvoiced->format('m-d-Y');
echo $DateInvoiced_date;
echo '<br />';
if ($DateInvoiced_date == $Today)
{
echo $DateInvoiced_date;
echo '<br />';
$ItemsRs=odbc_exec($conn,$ItemsSql);
while($row = odbc_fetch_array($ItemsRs))
{
$ItemID = odbc_result($ItemsRs,"ItemID");
if ($ItemID == 'Delivery')
{
echo 'Delivery';
}
}
}
}
I solved the issue using the INNER JOIN command. It is great because I don't have to do nested loops :)
Learned how to do it from W3Schools. http://www.w3schools.com/sql/sql_join_inner.asp
This is my current SQL Statement:
$TransactionSql = "SELECT apcshead.Key, apcshead.DateInvoiced, apcshead.InvNum, apcsitem.Headkey, apcsitem.ItemID FROM apcshead INNER JOIN apcsitem ON apcshead.Key=apcsitem.Headkey";
Is it possible to re-write the code below, maybe even with an if (result > 0) statement, in just one line (or simply shorter)?
// a simple query that ALWAYS gets ONE table row as result
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
I've seen awesome, extremely reduced constructs like Ternary Operators (here and here - btw see the comments for even more reduced lines) putting 4-5 lines in one, so maybe there's something for single result SQL queries like the above.
You could shorten
$query = $this->db->query("SELECT id FROM mytable WHERE this = that;");
$result = $query->fetch_object();
$id = $result->id;
to
$id = $this->db->query("SELECT id FROM mytable WHERE this = that")->fetch_object()->id;
but this, and the original code will emit errors, if any of the functions returns an unexpected response. Better to write:
$query = $this->db->query("SELECT id FROM mytable WHERE this = that");
if (!$query) {
error_log('query() failed');
return false;
}
$result = $query->fetch_object();
if (!$result) {
error_log('fetch_object() failed');
return false;
}
$id = $result->id;
I have the following inside a foreach loop (displaying my various videos), I'm trying to display some alternate text for the top three voted videos. What on earth am I doing wrong (a lot clearly)...
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
$row = #mysql_fetch_array($result);
if(in_array($video->getProperty('video_id')) == $row['video_id']) {
do this...
} else {
do this..
}
Firstly replace your code with some error preventing techniques like so!
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
{
$row = mysql_fetch_assoc($result); //Dont need the # restraint as the result is not false above.
//Also to get associate keys you need to use mysql_fetch_assoc
if($video->getProperty('video_id') == $row['video_id'])) //Remove the in array as your directly comparing the to entities with ==
{
//Match
}else
{
//Video does not match
}
}
Your main problem was the mysql_fetch_array(), Please research the differences with mysql_fetch_array() and mysql_fetch_assoc();
--
Edit: The way i would go
//Change the query and the loop way.
$sql = "SELECT video_id FROM videos WHERE displayable='y' AND video_id != '".(int)$video->getProperty('video_id')."' ORDER BY votes desc LIMIT 0,3";
if(false != ($result = mysql_query($sql))
//Use the # restraint if you have E_NOTICE on within E_Reporting
{
while($row = mysql_fetch_assoc($result))
{
//Print the $row here how you wish for it to be displayed
}
}else
{
//We have an error?
echo '<strong>Unable to list top rated videos, please check back later.</strong>'
}
}
mysql_fetch_array only returns a single row, you need to loop through your results to build an array containing the top three ids.
$sql = "SELECT video_id FROM videos WHERE displayable='y' ORDER BY votes desc LIMIT 0,3";
$result = mysql_query($sql);
while($row = #mysql_fetch_array($result)) {
$topthree[] = $row["video_id"];
}
Then you can use in_array but with the correct syntax:
if(in_array($video->getProperty('video_id'), $topthree)) {
do this...
} else {
do this..
}