MySQL Error #1064 Having trouble finding solution? [duplicate] - php

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I realize the error pertains to syntax - I am fairly new to MySQL; but I usually know my way around. This error has been plaguing me for days! Any and all help would be appreciated, thanks!
ERROR:
Connected successfully! 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 '' at line 1 USER EXISTS
CODE (I narrowed it down to these two functions, addUser() calls doesUserExist()):
function doesUserExist($user, $conn) {
try {
// Setting the query and runnin it...
$sql = "SELECT COUNT(email) FROM userinformation WHERE email = $user";
$result = $conn->query($sql);
// If it's greater than 0 then the account exists
if ($result != 0) {
echo "more than 0";
return true; // user exists
} else {
echo "0";
return false; // user does not exist
}
}
// Catching it if something went wrong.
catch(PDOException $e) {
echo $e->getMessage();
}
}
function addUser($user, $conn) {
echo $user;
// If user does not exist
if (doesUserExist($user, $conn) === false) {
// Add user to database (begin this process)
$sqlEntry = "INSERT INTO userinformation (email, password) VALUES('alexnord', 'password')";
$query = $conn->query($sqlEntry); // insert data into table
} else {
// Take to profile homepage
echo "USER EXISTS";
}
}

you forget single quotations for string input, your select query should be
$sql = "SELECT COUNT(email) FROM userinformation WHERE email = '$user'";

Related

how i can slove this error,SQLSTATE[42000]? [duplicate]

This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
Closed 2 years ago.
please help me to solve this error.i tired from searching solution...
error: 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 'WHERE name=NULL' at line 1
my database have 3 column=id(int),name(varchar),comment(varchar) and i want insert comment to it.
my php code :
<?php
include "./Config.php";
include './MyPDO.php';
$response = array() ;
$connect = MyPDO::getInstance();
$name = $_REQUEST['name'];
$comment=$_REQUEST['comment'];
$query = " INSERT INTO user "
. " (comment) "
. " VALUES "
. " (:comment) "
. " WHERE name=:name ";
$stmt = $connect->prepare($query);
$stmt->bindParam(":name",$name);
$stmt->bindParam(":comment",$comment);
try {
$stmt->execute();
$response['massage'] = "sucess";
echo json_encode($response);
exit;
} catch (PDOException $ex) {
$response['massage'] = "error";
$response['error']=$ex->getMessage();
echo json_encode($response);
}
Looks like you mixed the syntax here. You seem to want to update an existing record. Use
update user
set comment = :comment
where name = :name
insert if for creating a new record.
The insert into ... values() syntax does not take a where clause.
If you want to insert, then:
insert into user(name, comment) values(:name, :comment)
But actually it looks like you might want an update:
update users set comment = :comment where name = :name;
The former creates a new record in the table, with the given name and comment.
The latter modifies the already-existing record that has the same name and sets its comment value.

how to update table with session variable in php pdo?

i have one table called post_data, In that i want to update columns based on session variable.
this is my query.
$id = $_SESSION['userSession'];
$stmt = $user_home->runQuery("UPDATE post_data
set
cam_name='$cname',
cam_model ='$model',
cam_rent='$rent',
cam_img='$upic',
mobile='$umob'
upd_date='$jdate'
where userID='$id'
");
$stmt->bindParam(':cname',$camname);
$stmt->bindParam(':model',$modelname);
$stmt->bindParam(':rent',$rentpday);
$stmt->bindParam(':upic',$userpic);
$stmt->bindParam(':umob',$usermob);
$stmt->bindParam(":jdate",$upd_date);
if($stmt->execute())
{
$successMSG = "Record saved success";
}
else
{
$errMSG = "error while inserting....";
}
this is runQuery() implementation in USER class
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
i got error like this
Fatal error: Uncaught PDOException: 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 'upd_date='2017-09-24 21:29:18' where ' at line 8 in C:\xampp\htdocs\DSLR_proj\profile.php:97
You are missing , just after mobile='$umob'.
Also, $cname is not same :cname. I would prefer to use placeholder as ? instead of any specific string to avoid any typo.
Also, you are missing binding for userID column.
UPDATE post_data
set cam_name=?,cam_model =?, cam_rent=?, cam_img=?, mobile=?, upd_date=?
where userID=?
$stmt->bindParam(1,$camname);
$stmt->bindParam(2,$modelname);
$stmt->bindParam(3,$rentpday);
$stmt->bindParam(4,$userpic);
$stmt->bindParam(5,$usermob);
$stmt->bindParam(6,$upd_date);
$stmt->bindParam(7,$id); // you are missing this as well

PHP check to see if MySQL table exists [duplicate]

This question already has answers here:
How can I check if a MySQL table exists with PHP?
(12 answers)
Closed 7 years ago.
I'm trying to see if a table already exists and then act accordingly. I was unable to solve my problem from viewing previous posts.I'm aware of a secondary problem where the sql throws an error but I don't know why it throws. When I replace $thisTable with the actual string, it works. But my primary problem is not being able to detect if the table exists.
$thisTable = "testX";
$thisTable = preg_replace("/[^A-Z,a-z,0-9]/", '', $thisTable);
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SHOW TABLES LIKE ".$thisTable;
//I get an SQL error here?
$stmt = $conn->prepare($sql);
$stmt->execute();
$isThere = $stmt->num_rows;
if ($isThere > 0){
echo "Already exists."
} else {
echo "Doesn't exist."
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage() . "<br/>WITH QUERY: " . $sql;
}
You need quotes around the table name in the query.
$sql = "SHOW TABLES LIKE '$thisTable'";

Syntax error or access violation: 1064 don t get it?

the text i get in the browser:
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 ''users' WHERE 'username'= 'cAASDASD'' at line 1
maybe it is in this part?
otherwise i have no more 'WHERE'.
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT('id') FROM 'users' WHERE 'username'= ?");
$query->bindValue(1, $username);
try {
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1) {
return true;
}
else {
return false;
}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
in the real code you run there are 'single quotes' are used around table name, not backticks as in one posted here
And you have no idea where this error occurred because of the wrong way of using exceptions. So, as soon as you remove that useless try-catch, as soon you will be informed of the exact place where error occurred
The error doesn't relate to the snippet of PHP code you're showing. Going by the error message, it looks like you're using something like:
$query = $this->db->prepare("SELECT * FROM 'users' WHERE 'username' = ?");
Here, the table and column are both using single quotes rather than back ticks. What you want is:
$query = $this->db->prepare("SELECT * FROM `users` WHERE `username` = ?");

Why do I get error SQLSTATE42000 in PHP/MySQL

I am working on a project using PHP and MySQL.
I have an HTML table that has 3 columns into which I load data from my "Tasks" table in MySQL. The columns are: id, taskname and a button column that when clicked on, takes you to the Edit page for the relevant task (I pass the task id as a URL) - http://localhost/tasks/?edit&id=3
The problem arises when I try to load the details about this task. This is the code:
if(isset($_GET["id"]))
{
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$result = $pdo->prepare($sql);
$result->bindValue(":id", $_GET["id"]);
$result = $pdo->query($sql);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
foreach($result as $task)
{
$tasktext = $task["task"];
$id = $task["id"];
}
$title = "Edit task";
$action = "edittask";
$button = "Edit task";
include 'form.php';
exit();
resetParameters();
I get the following error:
Error trying to load task - 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 ':id' at line 1
When I replace the WHERE id = :id with WHERE id = 3 for example it works and loads the details about the task however I simply cannot get it to load the details about the task I have clicked on in the previous screen.
Could anyone spot anything wrong with my code/logic and point me in the right direction please?
You need to use execute() not query() when using prepared query's:
execute() PDOStatement::execute — Executes a prepared statement.
query() PDO::query — Executes an SQL statement.
Try:
<?php
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$query = $pdo->prepare($sql);
$query->bindValue(":id", $_GET["id"]);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
?>

Categories