php - sql select query where date is greater then, including php variables - php

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";

Related

PHP Multiple DB Connections Failing

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!';

MySQLI mysqli_store_result results with Malformed Packet error

I am in the process of converting some old MySQL code into MySQLI Prepared Statements and hit a snag:
If I run the same SQL code as prepared statement, I get a "Malformed Package" error. This happens even with extremely simple queries like "SELECT * FROM [TableName]".
I have the creation of the connection and setting of the Report level in a Seperate file altogether. So that code must be identicaly by definition.
As specific example, this code works:
$sql = "SELECT * FROM AngebotsDB";
$result = mysqli_query($link, $sql);
But this code:
$sql = "SELECT * FROM AngebotsDB";
// $result = mysqli_query($link, $sql);
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_execute($stmt);
$resultReference = mysqli_store_result($link); //throws exception
$result = mysqli_fetch_array($resultReference);
ends in:
Fatal error: Uncaught exception 'mysqli_sql_exception' with message
'Malformed packet' in /home/cgroschupff/public_html/custom_code/DB
structure.php:16 Stack trace: #0 /home/cgroschupff/public_html/custom_code/DB structure.php(16):
mysqli_store_result(Object(mysqli)) #1 {main} thrown in
/home/cgroschupff/public_html/custom_code/DB structure.php on line 16
All I could really find is some old information of this happening when Connecting to the DB.
Note that the used MySQLi/PHP version is rather old (5.2.17?). So this could be a "long ago fixed" bug?
If you initialize a statement than you have to call other functions according to mysqli_stmt class so your code should be .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$resultReference = mysqli_stmt_store_result($link);
Now if you try var_dump($resultReference) than return true or false .
if you want to show result with mysqli_fetch_array so you have to pass mysqli_result parameter so for this you have to use mysqli_stmt_get_result .
$sql = "SELECT * FROM AngebotsDB";
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt) ;
$output = mysqli_fetch_array($result) ;
Now you can see var_dump($output) than you have result .

Error: SQLSTATE[42000] When I try to update a value in a table [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 7 years ago.
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near ''1235'='1235'
WHERE username='wafflezzz'' at line 1' in
/home/wafflez3/public_html/Project SA Theme/ipn/set.php:14 Stack
trace: #0 /home/wafflez3/public_html/Project SA Theme/ipn/set.php(14):
PDOStatement->execute() #1 {main} thrown in
/home/wafflez3/public_html/Project SA Theme/ipn/set.php on line 14
I get that error when I use this code to change a null value to a value.
<?php session_start(); require "../pdo_connect.php"; $usrname = $_SESSION["username"]; ?>
<title>Loading...</title>
<?php
$checker = $conn->prepare("SELECT * FROM transactions WHERE payer_user=:username AND success='1'");
$checker->bindParam(":username", $usrname);
$checker->execute();
while ($row = $checker->fetch(PDO::FETCH_BOTH)) {
$paidscript = $row["item_name"];
$sql = $conn->prepare("UPDATE us SET :script=:script WHERE username=:userr");
$sql->bindParam(":userr", $usrname);
$sql->bindParam(":script", $paidscript);
$sql->execute();
echo "You can now view the script!";
}
$sql = $conn->prepare("UPDATE us SET :script=:script WHERE username=:userr");
Should probably be
$sql = $conn->prepare("UPDATE us SET script=:script WHERE username=:userr");
You're simply not meant to bind field names to parameters. If you do, it will give you an error like this.
To have a dynamic field name, you would have to do something like:
$paidscript = $row["item_name"];
$sql = $conn->prepare("UPDATE us SET {$paidscript}=:script WHERE username=:userr");
Although you shouldn't really be entering a field dynamically if it's from a user inputted value.
This
$sql = $conn->prepare("UPDATE us SET {$paidscript}=:script WHERE username=:userr");
Instead of this:
$sql = $conn->prepare("UPDATE us SET :script=:script WHERE username=:userr");

Catchable fatal error: Object of class mysqli could not be converted to string in what is ment buy it beind an object?

I have been on the site for some time now and I can't seem to get the idea that most of the similar questions are getting answers for this error:
Catchable fatal error: Object of class mysqli could not be converted to string
Saying it is an object. I am fairly new to PHP and it would really help if anyone could explain this to me. I am trying to retrieve data from my database and echo it in a table.
This is what I have done so far:
$dbcon=mysqli_connect("localhost","root","","technoage");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$results = mysql_query("SELECT * FROM items WHERE item_id = 1,$dbcon");
if(!$results)
{
die("Database query failed".mysql_error());
}
while($row = mysql_fetch_array($results))
{
echo $row['descreption']." ".$row['price']."<br/>";
}
You are connected with mysqli
but your are querying with mysql
$results = mysql_query("SELECT * FROM.....
rewrite your code with mysqli not mysql as you are mixing mysqli with mysql.
this
$results = mysql_query("SELECT * FROM items WHERE item_id = 1,$dbcon");
should be
$results = mysqli_query($dbcon, "SELECT * FROM items WHERE item_id = 1");
and this
while($row = mysql_fetch_array($results))
should be
while($row = mysqli_fetch_array($results))
This error is not caused by mixing mysql and mysqli. It's caused by inserting $dbcon into your SQL string itself, here:
$results = mysql_query("SELECT * FROM items WHERE item_id = 1,$dbcon");
// ^ here
The connection should be passed as the first argument with the query as the second. You're inserting it into the SQL string and passing it as a single argument, which means PHP tries to convert the object to a string.
Change to:
$results = mysqli_query($dbcon, "SELECT * FROM items WHERE item_id = 1");
As others point out, you need to change all mysql_ references to mysqli_ but this is your secondary problem. The immediate problem is the string issue and once that's fixed, you will encounter the mixing mysql problem.

PDO order by throws error

I am confused.
This is working:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
$stmt = $conn->prepare($sql);
$stmt->execute();
This is not:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);
$stmt->execute();
I have checked and set $orderbydateofupload by $orderbydateofupload='DESC', so it's definitely not null.
I get an error to the last line ($stmt->execute()):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DESC'' at line 1' in /home/gh6534/public_html/query.php:77 Stack trace: #0 /home/gh6534/public_html/query.php(77): PDOStatement->execute() #1 {main} thrown in /home/gh6534/public_html/query.php on line 77
I also tried to use the column as parameter:
$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute();
This does not throw an exception, but all items are queried without any sorting. What's wrong?
Try this
$orderbydateofupload = 'ASC'; //Or DESC
if($orderbydateofupload == 'DESC')
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
else
$sql = 'SELECT * FROM TABLE'
You can't bind identifiers with PDO because prepared statements can be used only with data, but not with identifiers or syntax keywords.
So, you have to use whitelisting, as shown in the example I posted before
That's why in my own class I use identifier placeholder, which makes whole code into one line (when you need to set the order by field only):
$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort);
but with keywords whitelisting is the only choice:
$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);

Categories