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";
}
Related
So I am trying to extract the maximum invoiceNo for current year and this is how I implemented it with PDO:
$sql = 'SELECT MAX(invoiceNo) AS invoiceId FROM invoices WHERE invoiceDate BETWEEN :yearStart AND :yearEnd HAVING invoiceId IS NOT NULL';
if($stmt = $pdo1->prepare($sql)){
$year = date("Y")."-01-01";
$stmt->bindParam(":yearStart", $year);
$year = date("Y")."-12-31";
$stmt->bindParam(":yearEnd", $year);
if($stmt->execute()){
if($stmt->rowCount() == 1){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$invoiceNo = $row['invoiceId'];
$response = date("Y").strval(++$invoiceNo);
}
else{
$response = date("Y")."-0";
}
}
}
However, $response keeps getting assigned to the else clause : .
This is how my DB looks like:
Hence I was expecting the $response to be 2022-2.
I think there is something wrong with my SQL query and I apologize for that, still learning the ropes!
$sql = "SELECT MAX(arbitInvoiceNo) AS invoiceId FROM invoices WHERE invoiceDate BETWEEN :dateStart AND :dateEnd HAVING invoiceId IS NOT NULL";
if($stmt = $pdo1->prepare($sql)){
$dateStart = date("Y")."-01-01";
$stmt->bindParam(":dateStart", $dateStart);
$dateEnd = date("Y")."-12-31";
$stmt->bindParam(":dateEnd", $dateEnd);
if($stmt->execute()){
if($stmt->rowCount() == 1){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$invoiceNo = $row['invoiceId'];
$response = date("Y")."-".strval(++$invoiceNo);
}
else{
$response = date("Y")."-0";
}
}
}
Changed the way I named the variables in PHP and the placeholders in the SQL query. Thank you ADyson for all the help!
Im currently new to php, i figured this is the right place to ask.
When i tried to echo $empshift variable. it says in the browsers console
("SELECT SHIFT_START FROM myilogin_46.DATE_TIME_RECORDS WHERE ID = ''
and r_status = 'A'").
As You can see it returns the string or the query itself, not the actual value of the query.
How do I do it so that $empshift would really return the value of the query (for example: in the database SHIFT_START column is a time datatype-> 08:30:00 in this format.).
I figured this was the reason why I can't subtract $empshift to $alterin.
foreach ($rs as $key => $value) {
$db = new Database();
$db->connect();
date_default_timezone_set('Asia/Ho_Chi_Minh');
$empshift = $db->select(array('myilogin_46.DATE_TIME_RECORDS'),'SHIFT_START',"ID = '".$id."' and r_status = 'A'");
echo $empshift; //SELECT SHIFT_START FROM myilogin_46.DATE_TIME_RECORDS WHERE ID = '' and r_status = 'A'<br />
$sched = $empshift;
$alterin = date('H:i:s',strtotime($value['alterIN']));//
echo $alterin;//08:33
echo $sched;
$late = $alterin-$sched;
$db->update_imp('myilogin_46.DATE_TIME_RECORDS',array(
'date_in'=>date('Y-m-d',strtotime($value['alterIN']))
,'time_in_info'=>'ALTERED IN'
,'time_out_info'=>'ALTERED OUT'
,'time_in'=>date('H:i',strtotime($value['alterIN']))
,'time_out'=>date('H:i',strtotime($value['alterOUT']))
,'date_out'=>date('Y-m-d',strtotime($value['alterOUT']))
,'late'=>$late
),"id = '".$value['dtrID']."' and id_emp = '".$value['empID']."' and R_STATUS = 'A'");
// echo date('H:i:s',strtotime($late));
$db->disconnect();
this is the select () function in the Database class:
public function select($table = array(), $column = '*', $where = null, $order = null, $limit = null){
$qry = 'SELECT '.$column.' FROM '.implode(', ',$table);
if($where != null){
$qry .= ' WHERE '.$where;
}
if($order != null){
$qry .= ' ORDER BY '.$order;
}
if($limit != null){
$qry .= ' LIMIT '.$limit;
}
// echo $qry.'</br></br>';
// exit();
if ($this->sql($qry)) {
return $qry;
} else {
echo 'dbselect sql error: '.$qry;
exit();
}
}
I got it, I didnt assign the query to as a variable. instead i used for each and a getResult function.
foreach ($rs as $key => $value) {
$db=new Database();
$db->connect();
$alterin= date('H:i:s', strtotime($value['alterIN']));
$db->select(array('myilogin_46.DATE_TIME_RECORDS'),'SHIFT_START'
,"ID = '".$value['dtrID']."' and R_STATUS='A'");
foreach ($db->getResult() as $key => $value) {
$shiftstart = $value['SHIFT_START'];
}
$late= $alterin - $shiftstart;
// if($shiftstart >= $alterin){
// $late= "00:00:00";
// }elseif ($shiftstart > $alterin) {
// # code...
// $late= $alterin - $shiftstart;
// }
echo $shiftstart;
echo $alterin;
echo $late; //
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
This question already has an answer here:
How to check fetched result set is empty or not?
(1 answer)
Closed 11 months ago.
What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...
This gets the match, adds it to my array and echoes the result as expected:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
if ($sth->fetchColumn()) {
echo 'not empty';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
return true;
}
echo 'empty';
$db = null;
return false;
You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do
if ($sth->rowCount() > 0) {
... got results ...
} else {
echo 'nothing';
}
Relevant documentation is here: PDOStatement::rowCount
If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.
count($sql->fetchAll(PDO::FETCH_ASSOC))
will return the number of rows returned.
You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
$db = null;
exit();
}
$result = $sth->fetch(PDO::FETCH_OBJ)
if(!isset($result->id_email))
{
echo "empty";
}
else
{
echo "not empty, value is $result->id_email";
}
$db = null;
Of course this is only for a single result, as you might have when looping over a dataset.
I thought I would weigh in as I had to deal with this lately.
$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");
$sql->execute();
$fetch = $sql->fetch(PDO::FETCH_ASSOC);
// if not empty result
if (is_array($fetch)) {
$_SESSION["userMember"] = $fetch["username"];
$_SESSION["password"] = $fetch["password"];
echo 'yes this member is registered';
}else {
echo 'empty result!';
}
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.
One more approach to consider:
When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.
$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
// non-repetitive markup code here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
I only found one way that worked...
$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");
//if (!is_array($quote)) { didn't work
//if (!isset($quote)) { didn't work
if (count($quote) == 0) { //yep the count worked.
echo 'Record does not exist.';
die;
}
Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).
$today = date('Y-m-d', strtotime('now'));
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today', $today, PDO::PARAM_STR);
if(!$sth->execute()) {
$db = null;
exit();
}
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$this->id_email[] = $row['id_email'];
echo $row['id_email'];
}
$db = null;
if (count($this->id_email) > 0) {
echo 'not empty';
return true;
}
echo 'empty';
return false;
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}