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!';
Related
The Problem:
I am trying to subtract 0.05 from the variable cash_amount in my database called users, and i am calling this file by ajax but nothing is occurring. To fix this, i opened the file in my browser and i got this error:
The Error:
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 '' at line 1
The Code:
PHP:
<?php
session_start();
$servername = "localhost";
$username = "myUser";
$password = "myPass";
$dbname = "myDBname";
$cash_amount = $_SESSION['cash_amount'];
// Create connection
$userid = $_SESSION['id'];
// You must enter the user's id here. /\
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$_SESSION['cash_amount'] -= 0.05;
$newAmount = $cash_amount - 0.05;
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
$result = $conn->query($sql);
if($result)
{
echo "5 cents have been subtracted!";
}
else
{
echo mysqli_error($conn);
session_start();
session_unset();
session_destroy();
}
$conn->close();
?>
Javascript/AJAX:
function countdownEnded() {
//make serverscreen dissapear
document.getElementById('serverScreenWrapper').style.display = 'none';
document.getElementById('serverScreenWrapper').style.opacity = '0';
document.getElementById("cashOutNumTwo").style.right = '150%';
document.getElementById("cashOutNumOne").style.right = '150%';
//start Timer
setInterval(gameTimer.update, 1000);
//make player move again
socket.emit('4');
socket.emit('6');
//make game appear
document.getElementById('gameAreaWrapper').style.opacity = 1;
//play sound
document.getElementById('spawn_cell').play();
//cut 5 cents from account - php function
$.ajax({
type: "POST",
url: 'http://cashballz.net/game/5game/subtract5.php',
data: { },
success: function (data) {
alert(data);
}
});
}
My Database:
My table is called users and its inside of the DB casball_accounts.
Here is the format:
id | first_name | last_name | email | password | cash_amount | 4 in between | hash | active
Conclusion:
I am pretty confused on why my php code isn't working, I have already tried searching for a fix and i found the words "SQL Injection" but I still didn't find the error. I am advanced at JS but a beginner to PHP, so please bear with me. Thanks!
You could simplify the query and do
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = $userid";
But to avoid the possibility of SQL Injection I would suggets also changing the code to use a parameterised and bound query like this
$sql = "UPDATE users SET cash_amount = cash_amount - 0.05 WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $userid);
$result = $stmt->execute();
You're interpolating data into the query, which, if that is what you want, you go with Mostafa's answer and put quotes around those values in case they're malformed. Which also means you have to check to see if they're legitimate values before putting them into the query.
However, they may also be subject to user input somewhere up the line, so do use PDO's prepared statements.
$sql = "UPDATE users SET cash_amount = :newAmount WHERE id = :userid";
$conn = $conn->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$conn->execute([':newAmount' => $newAmount, ':userid' => $userid])
...should take care of the issue. But making sure you have what tyou think you have can prevent a lot of red herrings.
The syntax error complains there's a problem near '' which means there is nothing following the point where it gets confused. I.e., it gets confused at the end of the query.
If $userid is blank, your SQL query will be
UPDATE users SET cash_amount = ... WHERE id =
This is clearly wrong syntax, because = requires two operands.
You need to make sure your $userid has a non-blank value.
The suggestions in other answers try to work around the issue by using quotes or query parameters, but the real problem is that you don't check that $userid has a value before you use it.
Replace
$sql = "UPDATE users SET cash_amount = '$newAmount' WHERE id = '$userid'";
instead
$sql = "UPDATE users SET cash_amount = $newAmount WHERE id = $userid";
This question already has answers here:
mysqli_stmt::execute() expects exactly 0 parameters, 1 given
(4 answers)
Closed 1 year ago.
So I am new to PHP and I have been on a roll lately developing a website. My question is this. I have all users listed inside of a field in one table.
This is a list of one of these fields: admin, user1, user2, user3.
Now what I need to do is take them users from that ONE field, I am guessing put them into an array and then search each user inside of another table called users and then list the users info such as their rating and bio.
I reposted this with pictures to help you get an idea of what I am looking to accomplish.
I am looking to get the users from this table listed inside of that cell
jobs Table
and find them in this table and then list them
users table
Hey I have edited the code in the following way and I am getting an error.
$jobID = 1;
$jq = $con-> prepare('SELECT applied_names FROM jobs WHERE jobID=1 LIMIT 1');
$jq-> execute();
$jq-> bind_result($usernames);
$jq-> fetch();
$jq-> close();
$stm = $con->prepare("SELECT username FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
$result = $stm->get_result()->fetch_assoc();
$stm->close();
The warning says:
Warning: mysqli_stmt::execute() expects exactly 0 parameters, 1 given on line 14
You can use a subquery and the keyword IN for this:
SELECT * FROM meta_table WHERE userID IN (SELECT id FROM users)
If you post table & column names, I will be able to give you a more precise query.
EDIT:
after seeing your edited post with the images, this way is not possible. you would still be able to use the IN after you have got the field with the usernames in PHP.
$usernames = $row['applied_names'];
$stm = $pdo->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
And for mysqli:
$usernames = $row['applied_names'];
$stm = $con->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->bind_param('s', $usernames);
$stm->execute();
In my opinion, you should have a users_jobs table with columns id userID & jobID then you can use queries like this:
SELECT username,email,jobName,jobStatus FROM users_jobs
JOIN users ON users.id = users_jobs.userID
JOIN jobs ON jobs.id = users_jobs.jobID
This will produce one row with all the columns you have specified in the SELECT
Just try that :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name, rating, bio FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row["name"]. " - rating: " . $row["rating"]. "bio " . $row["bio"]. "....<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
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 need to SELECT and show all entries written by specific user and number of his/her total entries
<?php include 'helperl.php'; include 'dbconn.php';
$name=$_GET['id'];
$sql="SELECT * FROM entries WHERE writer_user LIKE '%$name%'";
$result=$conn->query($sql);
$num_entry= count($result);
echo "$num_entry";
?>
First the LIKE option that you did will get you all the name that contain $user
Your query should be like
SELECT nb
FROM (SELECT writer_user,count(*) as nb
FROM entries
WHERE writer_user=you_var
Group BY writer_user)
For getting all the entries of specific user
SELECT *
FROM entries
WHERE writer_user=you_var
u can do a join in one query to get the information you wanted but there will be a duplication in the count attribut.
exemple :
entrie count
entrie1 4
entrie2 4
entrie3 4
entrie4 4
hope i helped you.
you should use SQL COUNT function to do this (SQL COUNT function
)
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Your code can look like this
<?php
try {
$name = htmlentities(strip_tags($_GET['id']));
$sql = "SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%$name%'";
// create pdf instance
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%name%'");
$stmt->bindParam('name', $name);
$stmt->execute();
$result = $conn->query($stmt)->fetchAll();
var_dump($result);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
?>
I am not sure how to go about this in PHP & MySQL;
But basically, I just want to check to see if a row exists in a table, and if it does, return a error, example:
$exists = MYSQL CODE TO CHECK HOW MANY ROWS INCLUDE BADGE_ID
if($exists >= 1)
{
$errors[] = "Exists.";
}
Something like that, because I'm coding a small shop script and I want it to check to make sure that they don't already have the badge_id. Structure of the db is user_id and badge_id (user_id = 1, badge_id = 1; for an example)
//Mysql
$res = mysql_query("YOUR QUERY");
if(mysql_num_rows($res) > 0) {
$errors[] = "Exists.";
}
//PDO
$query = $db->prepare("YOUR QUERY");
$ret = $query->execute();
if($ret && $query->rowCount() > 0) {
$errors[] = "Exists.";
}
for this query as
$query=mysql_query("SELECT * from table WHERE userid = 1 AND badgeid = 1");
and in php
if(mysql_num_rows($query)>0){
// whatever you want if match found
}else{
echo "No match Found".
}
$sql = "SELECT COUNT(*) FROM `table_name` WHERE `user_id` = '1' AND `badge_id` = '1' "
$exists = mysql_query($sql) ;
if(mysql_num_rows($exists) >= 1) {
$errors[] = "Exists.";
}else {
// doesn't exists.
}
Try using PDO instead of the old mysql_query() functions for they are deprecated since PHP 5.5.
For a simple query:
$slcBadge = $con->query('SELECT badge_id FROM badges');
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Or if you want to fetch all rows from a single user:
$sqlBadge = 'SELECT id_badge FROM badges WHERE id_user = :idUser';
$slcBadge = $con->prepare($sqlBadge);
$slcBadge->bindParam(':idUser', $idUser, PDO::PARAM_INT);
$slcBadge->execute();
if ($slcBadge->rowCount() > 0) {
$errors[] = 'Exists.';
}
Notice that in the second piece of code I used prepare() and execute() rather than query(). This is to protect you query from SQL injection. By using prepare() you fix the construct of your query so if a user enters a query string as a value, it will not be executed. You only need to prepare a query if a user can enter a value which will be used in your query, otherwise query() will do just fine. Check out the injection link for more detailed info.
Your version of PHP is important:
mysql_* functions are deprecated as of 5.4, and
Removed as of 5.5
It is advised to either implement PDO or Mysqli
mysql:
This extension is now deprecated, and deprecation warnings will be generated when connections are established to databases via mysql_connect(), mysql_pconnect(), or through implicit connection: use MySQLi or PDO_MySQL instead
Dropped support for LOAD DATA LOCAL INFILE handlers when using libmysql. Known for stability problems
Added support for SHA256 authentication available with MySQL 5.6.6+
For reference please see the changelog
Structuring your Query
First of all I'm assuming you are indexing your fields correctly refer to this article I posted on Stack Exchange.
Second of all you need to consider efficiency depending on the volume of this table: doing a SELECT * is bad practice when you only need to count the records - mysql will cache row counts and make your SELECT Count(*) much faster. with indexes this is furthermore efficient.
I would simply consider something along the line of this:
$dsn = 'mysql:host=127.0.0.1;dbname=DATABASE';
$db = new PDO($dsn, 'username', 'password', array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
));
NOTE:
where host=127.0.0.1 if your user has been granted access via localhost then you need this to state localhost - or grant the user privileges to 127.0.0.1
NOTE:
with SET NAMES there is also a bug with the PDO driver from 5.3 (I believe) whereby an attacker can inject nullbytes and backspace bytes to remove slashing to then inject the query.
Quick example:
// WARNING: you still need to correctly sanitize your user input!
$query = $db->prepare('SELECT COUNT(*) FROM table WHERE user_id = ? AND badge_id = ?');
$query->execute(array((int) $userId, (int) $badgeId));
$total = $query->fetchAll();
$result = mysql_query("SELECT COUNT(*) FROM table WHERE userid = 1 AND badgeid = 1 LIMIT 1") or die(mysql_error());
if (mysql_result($result, 0) > 0)
{
echo 'exist';
}
else
{
echo 'no';
}