I need to insert data into one of MySql cell that contains the current datetime, but i'm not getting it. The unique thing i get is a "Fatal error: Uncaught Error: Object of class DateTime could not be converted to string" at mysqli_query line.
I saw a solution that contains a fixed date like "DateTime('2000-01-01')", but i need the "now" datetime.
$saleend = new DateTime();
date_add($saleend,date_interval_create_from_date_string("$saledays days, $salehours hours, 00 minutes, 00 seconds"));
$saleend->format('Y-m-d H:i:s');
mysqli_query($conn, "UPDATE tableName SET SALEEND = '$saleend' WHERE ID = '$id'");
I strongly recommend not using string concatenation in your application, instead use the much safer prepared statements. I've crafted a prepared statement and test it's operation:
<?php
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("127.0.0.1", "test", "password", "testdb");
$saleend = new DateTime();
$saledays = 1;
$salehours = 10;
date_add($saleend,date_interval_create_from_date_string("$saledays days, $salehours hours, 00 minutes, 00 seconds"));
/* Use a prepared statement */
$stmt = $mysqli->prepare("UPDATE tableName SET SALEEND = ? WHERE ID = ?");
$id = 1;
$timechange = $saleend->format('Y-m-d H:i:s');
// The "si" stands for $saleend is a string ("s") and $id is an integer ("i").
$stmt->bind_param('si', $timechange, $id);
$stmt->execute();
print $stmt->error; //to check errors
You can remove the mysqli_report() and print $stmt->error; line once you have debugged the application.
The prepare() line sets up your substitutions. Then the bind_param() does the swaps server side where it is safer. The execute() sends the query to the server.
Here is the table before I ran this code:
ID
SALEEND
1
2022-01-03 01:14:47
Then after:
ID
SALEEND
1
2023-01-04 16:40:51
Related
So I am creating a cronJob that will select ALL the users from my user table and then store the users full names in a variable. All that happens inside a while loop, inside the same loop I am selecting EVERYTHING from my customerLeads tables where the assignedTo column is equal to the users full name. Then inside this loop I want to record the customerName and store them all inside an array. So each user will have it's own array which has all the customersNames inside.
The purpose of this is to run this every morning so the users will get an email if they haven't updated a customerLead in over 2 days.
However I keep getting this error;
Fatal error: Uncaught Error: Call to a member function fetch() on boolean in /.../customerLeadReminder.php:18 Stack trace: #0 {main} thrown in /homepages/.../customerLeadReminder.php on line 18
I've had a look around online and everything says that it's the connection not working, but I've checked and the connection is running fine...
Question: Why does this error appear and what I am doing wrong?
<?php
//Error Reporting
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
require '../includes/conn.php';
$userList = $salesConn->query("SELECT `email`, `firstname`, `lastname` FROM `users`");
while ($uRow = $userList->fetch()) {
$user_name = $uRow['firstname']." ".$uRow['lastname'];
print_r($uRow);
$customerList = $salesConn->query("SELECT * FROM `customerLeads` WHERE curdate() >= (dateUpdated + interval 2 day) AND `assisgnedTo` = '$user_name' ORDER BY `customerID` DESC");
// show this on error
if (!$customerList) {
// For PDO:
echo $salesConn->errorInfo();
}
while ($cRow = $customerList->fetch()) {
$leadID = $cRow['customerID'];
$firstName = $cRow['customerFirstName'];
$lastName = $cRow['customerLastName'];
$tele = $cRow['customerTel'];
....
$dateCreated = $cRow['dateCreated'];
$dateUpdated = $cRow['dateUpdated'];
}
}
?>
By printing $uRow it shows:
Array ( [email] => joe.blogs#outlook.com [0] => joe.blogs#outlook.com [firstname] => Joe [1] => Blogs [lastname] => Blogs [2] => Blogs )
Connection Page is:
<?php
$salesConn = new PDO('mysql:host=HOST;dbname=DBNAME', 'USERNAME', 'PASSWORD');
$salesConn->setAttribute(PDO::ATTR_ERRMODE);
?>
New Error: Warning: PDO::setAttribute() expects exactly 2 parameters, 1 given in /homepages/38/d735513801/htdocs/includes/conn.php on line 8
SELECT * FROM `customerLeads` WHERE curdate() >= (dateUpdated + interval 2 day) AND `assisgnedTo` = '$user_name' ORDER BY `customerID` DESC
You used two times WHERE clause. You had a syntax error in your mysql. And also better use parentheses in your queries when you want to compare the result of a number calculation.
Try this to get a proper error message from MySQL
$customerList = $salesConn->query("SELECT * FROM `customerLeads` WHERE curdate() >= dateUpdated + interval 2 day AND WHERE `assisgnedTo` = '$user_name' ORDER BY `customerID` DESC");
// show this on error
if (!$customerList) {
/***
* NOTE: in a perfect world this should be:
* error_log(print_r($salesConn->errorInfo(),true)); OR
* error_log(print_r($salesConn->error,true));
***/
// For MySQLi:
echo $salesConn->error;
// For PDO:
echo $salesConn->errorInfo();
}
This is a tester script to establish what is wrong with your SQL.
localhost, DBNAME, USERNAME, PASSWORD are hardcoded values that the OP has not given and so the OP needs to update these themself.
This script below uses proper PDO and Exceptions. Get used to using Exceptions. Read about them, Learn them. This script also properly uses Prepared Statements - You really really (really) should be using Prepared Statements in your SQL.
<?php
error_log( 'php version: ', phpversion());
try {
$salesConn = new PDO('mysql:host=localhost;dbname=*DBNAME*;charset=utf8', '*USERNAME*', '*PASSWORD*');
error_log( 'client version: ', $salesConn->getAttribute(PDO::ATTR_CLIENT_VERSION));
error_log( 'server version: ', $salesConn->getAttribute(PDO::ATTR_SERVER_VERSION));
$salesConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$salesConn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $err) {
error_log(print_r($err->getMessage(),true));
die('Error log ONE was generated.');
}
$sql = "SELECT * FROM `customerLeads` WHERE CURDATE() >= (dateUpdated + INTERVAL 2 DAY) AND `assisgnedTo` = :assigned ORDER BY `customerID` DESC"
$user_name = "Set ths value to whatever the username is you want to check";
try
{
$stmt = $salesConn->prepare($sql);
$stmt->bindValue(':assigned', $user_name, PDO::PARAM_STR);
$stmt->execute();
// The below result can be put into a loop to output each $row in turn.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $err)
{
error_log(print_r($err->getMessage(),true));
error_log(print_r($salesConn->errorInfo(),true));
die('Error log TWO was generated.');
}
echo 'done. Got this far, everything worked!';
Already read all the other treads regarding this matter, but I cant find an answer that includes php variables.
I want to select the first 100 new records after a certain date of my database. I can't get it to work.
$connStr =
'odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq='.$ini_project['general']['document_location'].';';
$dbh = new PDO($connStr);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$time = strtotime('6-8-2017 21:52:00');
$date = date('j-n-Y H:i:s',$time);
$sql1 = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > `$date`";
$result = $dbh->query($sql1);
while($row = $result->fetch()) {
print_r($row);
}
I'm able to select records from another field in the table (WHERE value > 200 for example) but not based on the date column in my table.
I also tried without `` and:
$sql1 = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > DATE `$date`";
All give the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 0 [Microsoft][ODBC
Microsoft Access Driver] Syntax error (missing operator) in query
expression 'Systeemtijd > 6-8-2017 21:52:00'. (SQLPrepare[0] at
ext\pdo_odbc\odbc_driver.c:206)' in
C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php:65
Stack trace: #0
C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php(65):
PDO->query('SELECT TOP 100 ...') #1 {main} thrown in
C:\Bitnami\wampstack-5.6.30-1\apache2\htdocs\php7\DataBuilt\Larissa_Connector\data_uploader.php
on line 65
Passing variables like this is not a good idea, you always have to be aware of how to correctly escape them, try using PDO::prepare:
/* Execute a prepared statement by passing an array of values */
$sql = "SELECT TOP 100 * FROM $full_table_name
WHERE Systeemtijd > :date";
$sth = $dbh->prepare($sql);
$sth->execute(array(':date' => $date);
$red = $sth->fetchAll();
http://php.net/manual/en/pdo.prepare.php
Dates in Access SQL should be either #yyyy/mm/dd# or #mm/dd/yyyy#. Any other date format causes problems.
$date = date('#y/n/j- H:i:s#',$time);
$sql1 = "SELECT TOP 100 * FROM `$table_name $table_number` WHERE Systeemtijd > $date";
I am trying to make a price slider with PHP and SQL , but i have a problem when i have some problem in this code
$query = mysql_query("SELECT * FROM price WHERE phone_price BETWEEN" .$from. "AND" .$to. );
while($row = mysql_fetch_array($query)){
print $row['phone_name'];
print $row['phone_price'];
print '';
}
I want to run the SQL query like SELECT * FROM price WHERE phone_price BETWEEN 300 AND 500
I am making a beta version therefore i am accepting the $from and $to values from <input> , i think i am making the error in inserting the variable in mysql_query .
THE ERROR -Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\login\slide\slide.php on line 28
You have a mistake in your query. Spaces needed after BETWEEN and AND. Otherwise php reads your query like ...BETWEEN123AND1234.... And you should better use quotes to place vars:
$query = mysql_query("SELECT * FROM `price` WHERE `phone_price` BETWEEN '".$from."' AND '".$to."'");
Use PDO build-In object. mysql_ functions were deprecated.
Initialize connection.
$dsn = "mysql:host=localhost;dbname=my_database";
$pdo = new PDO($dsn, $login, $password);
Use prepare statement.
$sh = $pdo->prepare("SELECT * FROM price WHERE phone_price BETWEEN :from AND :to");
Bind values and value types.
$sh->bindParam(':from',$from,PDO::PARAM_INT);
$sh->bindParam(':to',$to,PDO::PARAM_INT);
Fetch results into assoc array.
$res = $sh->fetch_all(PDO::FETCH_ASSOC);
Good Luck
I've got the following PDO statement:
$myquery = SELECT * FROM DATABASE WHERE TABLE(Date) > 2014-04-07
$stmt = $this->pdo->prepare($myquery);
$stmt->execute();
I get the following error:
Operand type clash: date is incompatible with int
How is it possible to compare a Date in PDO?
Surround the date in single quotes when comparing:
$myquery = "SELECT * FROM DATABASE WHERE TABLE(Date) > '2014-04-07'";
I would try it like:
$myquery = SELECT * FROM table WHERE Date > ?
$stmt = $this->pdo->prepare($myquery,array('2014-04-07'));
$stmt->execute();
even better would be a non string for the date i.e. a datetime-object
I have a problem with mysql_query
I tried to find members who are online, there is a field "Online" in the members table are always updated with the time server. This is the query.
$ now = time ();
$ olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$ now')> 10"));
in phpmyadmin there are 7 members in accordance with the above query. tp I get a value of 0. what is wrong with my code. tq for the answer and sorry for bad english
You should try and always use Mysqli these days as before long Mysql will be gone completely. Mysqli example of your code:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$now = time(); // The time now for query calc
$gender = "Man"; // Gender for query
$stmt = $mysqli->stmt_init(); //Initialise statement
$stmt->prepare("SELECT * FROM members WHERE gender = ? AND (online - ?)> 10"); //Prepare the query
$stmt->bind_param('ss', $gender, $now); //Assign the query parameters
$stmt->execute(); // Execute the query
$stmt->store_result(); // store result of prepared statement
echo $stmt->num_rows;
$stmt->free_result(); //free up the $stmt var
Variable names cannot contain spaces, so your variable names are invalid. It should be $now or $_now and NOT $ now. See Language variable basics for more information:
Correct code :
$now = time ();
$olline = mysql_num_rows (mysql_query ("select * from members where gender = 'Man' and (online - '$now')> 10"));
Also , avoid using mysql_ functions cause they are deprecated. Use mysqli_ or PDO.
I am not sure, I have clearly understood your question.
If I have understood correctly, you want to display the online available members.
Do you have any flag for checking if the member online or not? If there is a flag then use that flag and filter by online status. This how we have to do for chat operations.
I am not sure, why you going with subtraction.