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();
}
?>
Related
I'm attempting to run both query to different table.
As tbl_invoice are inserted, invoice_id is created from first query (first one works) but when I put another query for tbl_invoice_details I think it doesn't actually pass the previous invoice_id value, tried with if($invoice_id != null){...} but this query doesn't seem to work for tbl_invoice_details.
Any help would be appreciated, thanks.
include_once 'connectdb.php';
$id = $_GET['id'];
$select = $pdo->prepare("SELECT * FROM tbl_product WHERE barcode=$id");
$select->execute();
$row = $select->fetch(PDO::FETCH_OBJ);
// FOR TBL_INVOICE
$variables
...
$insert = $pdo->prepare("INSERT INTO tbl_invoice(customer_name,order_date,subtotal,tax,discount,total,paid,due,payment_type,profit) values(:cust,:orderdate,:stotal,:tax,:disc,:total,:paid,:due,:ptype,:profit)");
$insert->bindParam(':cust',$customer_name);
$insert->bindParam(':orderdate',$order_date);
$insert->bindParam(':stotal',$subtotal);
$insert->bindParam(':tax',$tax);
$insert->bindParam(':disc',$discount);
$insert->bindParam(':total',$total);
$insert->bindParam(':paid',$paid);
$insert->bindParam(':due',$due);
$insert->bindParam(':ptype',$payment_type);
$insert->bindParam(':profit',$profit);
$insert->execute();
// FOR TBL_INVOICE_DETAILS
$invoice_id = $pdo->lastInsertId();
if($invoice_id != null){
$rem_qty = $stock - $qty;
$update = $pdo->prepare("UPDATE tbl_product SET pstock='$rem_qty' WHERE barcode='".$id."'");
$update->execute();
$insert = $pdo->prepare("INSERT INTO tbl_invoice_details(invoice_id,product_id,product_name,qty,price,order_date,values(:invid,:pid,me,:qty,:price,:orderdate,:profit)");
$insert->bindParam(':invid',$invoice_id);
$insert->bindParam(':pid',$pid);
$insert->bindParam(':pname',$productname);
$insert->bindParam(':qty',$qty);
$insert->bindParam(':price',$total);
$insert->bindParam(':orderdate',$order_date);
$insert->bindParam(':profit',$profit);
$insert->execute();
}
?>```
enable PDO error reporting:
include_once 'connectdb.php';
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$id = $_GET['id'];
when a SQL error occurs, it will get thrown as an exception. if we don't enable PDO error reporting, then the code needs to check the return from each SQL call to see if an error occurred.
The question here isn't "how to get multiple SQL query to different table". The real question is "how do I see what SQL error occurred".
<?php
try
{
global $db;
$user = 'postgres';
$password = '*****'; //For security
$db = new PDO('pgsql:host=localhost;dbname=dnd', $user, $password);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $ex)
{
echo 'ERROR!!: ' . $ex->getMessage();
die();
}
$table = htmlspecialchars($_REQUEST['table']);
$idNum = htmlspecialchars($_REQUEST['id']);
try {
//$query = "SELECT * FROM $table WHERE id = $idNum"; This works
//$query = "SELECT * FROM $table WHERE id = :number"; This works
$query = "SELECT * FROM :tableName WHERE id = :number";
$statement = $db->prepare($query);
$statement->bindValue(":tableName", $table, PDO::PARAM_STR);
$statement->bindValue(":number", $idNum, PDO::PARAM_INT);
$statement->execute();
$info = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $excep) {
echo "Opps: " . $excep->getMessage();
die();
}
Okay I'm going crazy here trying to get this to work.
I have a database set up that I need to query from. I receive the query from an AJAX request with the name of the table I want and the id for the item. When I try to query with both variables, the binding does not occur in the prepared statement and instead I get this error code
Opps: SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1" LINE 1: SELECT * FROM $1 WHERE id = 1 ^
When I have just the straight PHP variables it works fine so I know it can work, but when I want to bind multiple it seems to fail and give a variable number as above.
I can also get it to work if I simply have one of the variables bound, such as the second commented out query in the code - this only works tho if I have the variable I want at the end and not if I wanted to lookup the table spot. (I.E.
$query = "SELECT * FROM :tableName WHERE id = $idNum"; does not work)
I need to cleanse the variables to prevent SQL injection, but I can't do that without binding the variables in a prepared statement. Any help would be appreciated!
According to the PHP manual you can't bind a tablename. As you mentioned it, you can replace it by a variable, but you can't replace it with a placeholder.
So the only solution that will work for you is the query you have above:
$query = "SELECT * FROM $table WHERE id = :number"
This will be what you're looking for. If you want to make it safe for injection, you have to find another way. (Regex for example).
Ref: http://us3.php.net/manual/en/book.pdo.php#69304
I'm trying to insert variables into my database where the user data comes from $_SESSION['user'].
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to Login");
}
$user = $_SESSION['user'];
~calculations done~
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
$query_params = array(
':role' => $varRole,
':roleSub' => $varRoleSub
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query 3: " . $ex->getMessage());
}
I keep getting this error:
Failed to run query 3: 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 'WHERE user = Array' at line 1
I can not see where my WHERE clause is failing on me.
Any help would be greatly appreciated!!!
You cannot have a WHERE clause in an INSERT statement.
You're either looking for:
UDPATE db SET role = '$varRole', rolesub = '$varRoleSub' WHERE user = $user
Or:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
Or if you're feeling extra saucy, and user is your PK:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
ON DUPLICATE KEY UPDATE role = '$varRole', rolesub = '$varRoleSub'
INSERT queries do not and can not have a WHERE clause. This is the cause of the MySQL syntax error. If you need to insert based on some condition, you need to do that logic before the INSERT query.
If you want to do an UPDATE query then you can use the WHERE clause, however, the MySQL error shows $_SESSION['user'] is an array, which can't be put directly into SQL, so you'll need to access one of its elements such as $_SESSION['user']['id'].
First of all, IF you could have a WHERE in the same query as an INSERT, variables need to be separate from the string (outside of the quotes). BUT you CANT put a where clause into an INSERT.
So you could change this line:
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
to:
$query = "INSERT INTO db (role,rolesub) VALUES (" . $varRole . ", " . $varRoleSub . ")";
I am making a game for class and I have added a commenting system to go with it. I am now wanting to add the ability to report the comment.
I have added a column in the comments table called report_active and my idea was to set this to 1 when it is active (meaning it has been reported) and 0 when it isn't. Then just list in the adminCP all of the comments with an active report on them.
I have made a file called report_comment.php which I intend to only be used to run the queries then redirect back to another page.
This is my report_comment.phppage:
<?php
require_once('db_connect.php');
require_once('security.php');
if (isset($_GET['id'])) {
$report_active = 1;
$id = $_GET['id'];
$select = $db->query("SELECT * FROM comments WHERE id = ?");
$select->bind_param('i', $id);
if ($select->execute()) {
if ($select->num_rows) {
// Run the update query
$update = $db->query("UPDATE comments SET report_active = ? WHERE id = ?");
$update->bind_param('ii', $report_active, $id);
if ($update->execute()) {
header('Location: comments.php');
die();
}
}
}
}
?>
What am I doing wrong? As this is the error I am returned with:
Fatal error: Call to a member function bind_param() on a non-object
$select = $db->query("SELECT * FROM comments WHERE id = ?");
^^^^^---execute the query immediately
You want
$stmt = $db->prepare("SELECT * FROM comment WHERE id = ?");
^^^^^^^---note the diff
instead. Plus, you should be checking for failure, e.g.
if ($stmt === false) {
die("Prepare failed with error: " . $db->errorInfo);
}
or similar for your particular DB library.
I can't make the counter add 1 into the DB and the value increment every time when somebody go to the page... only works when is reloaded.
Where is the error in my code? Can you help me with this issue?
I don't know if you need my entire html page, if you want I page it. the url have the id is show like this: post.php?id_blog=4
THe code:
<?php
try {
$query = "SELECT id_blog, blog_titulo, blog, vistoblog FROM BLOG WHERE id_blog = ?";
$stmt = $conn->prepare( $query );
$stmt->bindParam(1, $_REQUEST['id_blog']);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id_blog = $row['id_blog'];
$blog_titulo = $row['blog_titulo'];
$blog = $row['blog'];
$vistoblog = $row['vistoblog'];
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
try{
$visto = $vistoblog + 1;
$sql = "UPDATE BLOG SET
vistoblog = :vistoblog
WHERE id_blog = :id_blog";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':vistoblog', $visto, PDO::PARAM_STR);
$stmt->bindParam(':id_blog', $id_blog, PDO::PARAM_INT);
$stmt->execute();
}catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
?>
I recommend making your SQL just like this:
UPDATE BLOG SET
vistoblog = vistoblog + 1
WHERE id_blog = :id_blog
The reason is to avoid a race condition. What if two people visit the page simultaneously, and both PHP threads read vistoblog value 123, add 1, and both try to increment it to value 124?
By using the expression above, you don't have to read the current value, and you avoid the chance of a race condition like that.