At the moment, I have two queries. The first selects a column from a row. The second then deletes that row. As both queries deal with the same row, I was wondering if it was possible to execute both queries in one (to reduce the amount of code).
I had a look at SELECT then immediately DELETE mysql record and tried Whatever Kitchen's answer
This was my code beforehand (which works fine):
$stmt = $con->prepare("SELECT number FROM viewings WHERE username=:user");
$stmt->bindParam(':user', $user);
$stmt->execute();
$row = $stmt->fetch();
$result = $row['number'];
$stmt = $con->prepare("DELETE FROM viewings WHERE username=:user");
$stmt->bindParam(':user', $user);
$stmt->execute();
echo $result;
This was my code after trying the answer:
$stmt = $con->prepare("DELETE FROM viewings WHERE username=:user IN (SELECT number FROM viewings WHERE username=:user LIMIT 1)");
$stmt->bindParam(':user', $user);
$stmt->execute();
$row = $stmt->fetch();
$result = $row['number'];
echo $result;
However, I receive these errors:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 1235 This version
of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery''
in /home//public_html/page.php:47
Stack trace:
0 /home//public_html/page.php(47): PDOStatement->execute()
1 {main} thrown in /home//public_html/page.php on line 4
You can try using the EXISTS condition:
DELETE FROM viewings WHERE EXISTS (SELECT * FROM viewings WHERE username=:user LIMIT 1)
Source: SQL EXISTS condition
Related
I made this code to display my user's details if I search for their email.
file.php
$sql = "SELECT * FROM users WHERE email='$email'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result2 = $stmt->get_result();
file.html
while ($row = $result2->fetch_assoc()) { //results }
The problem with this code is that I get always a fatal error.
Fatal error: Uncaught Error: Call to a member function fetch_assoc() on null in ____ Stack trace: #0 {main} thrown in ______
Even though my script works perfectly because when I am searching for my users detail it shows them as expected.
What do they mean with this error? Can I get SQL Injected if I stay it like this? How can I remove this error?
1.) Fix binding your email parameter....
$sql = "SELECT * FROM users WHERE email='?'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result2 = $stmt->get_result();
2.) For error you're getting i assume you get some error, you should check for $result2, if it's false > that means error
My file should get all users with this id (It's only one since id is unique in this table) and prepare a statement to execute later. When I execute it I get this error:
Fatal error: Uncaught Error: Call to a member function execute() on
boolean in C:\xampp\htdocs\Gamanware.ga\Admin\update.php:7 Stack
trace: #0 {main} thrown in
C:\xampp\htdocs\Gamanware.ga\Admin\update.php on line 7.
And I can't see anything wrong with it. The id is alright (I echo it out to be sure), Im not using reserved words and have made sure that it won't matter anyway, but I still get this error. I have been on several forums and many questions have not worked for me. I hope some of you can! My code:
<?php
require '../includes/login_system.dbh.php';
$id = $_GET['id'];
$sql = 'SELECT * FROM `users` WHERE `id`=:id';
$statement = $conn->prepare($sql);
$statement->execute([':id' => $id ]);
Try the code below and see if it helps
require '../includes/login_system.dbh.php';
$sql= "SELECT * FROM users WHERE id = :id";
$statement = $conn->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$id = $_GET['id'];
$statement->execute();
You can also do an if else statement with your execute like so to see what it gives you.
require '../includes/login_system.dbh.php';
$sql= "SELECT * FROM users WHERE id = :id";
$statement = $conn->prepare($sql);
$statement->bindParam(':id', $id, PDO::PARAM_INT);
$id = $_GET['id'];
if ($statement->execute()) {
echo "Success";
} else {
echo "Failed";
}
I want to prepare a mysql script that first checks the id of the user based on given email and later on use this found id in the next query. What I did so far is as follows:
$find_id = "SELECT id from client
WHERE email = ? ";
$statement = $mysqli->prepare($find_id);
$statement->bind_param("s", $client_mail);
$statement->execute();
$statement->bind_result($id);
$statement->free();
$sql = "SELECT client_name, contact_name from client_addr
WHERE client_id = ? AND is_actual < ? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("is", $id, "Y");
$stmt->execute();
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
echo json_encode($result);
but now I'm getting the error related to this line:
$statement->free();
that says Call to undefined method mysqli_stmt::free() in.
However, when I remove this line I'm getting the error:
Uncaught exception 'mysqli_sql_exception' with message 'Commands out of sync; you can't run this command now'
on this line:
$stmt = $mysqli->prepare($sql);
How can I fix it?
I believe the function you're trying to use would be mysqli_stmt::free_result(). You'll need to change this line:
$statement->free();
To:
$statement->free_result();
The second Uncaught exception occurs because mysqli is an unbuffered SQL query handler, so you should store your results if you're looping simultaneous executions with something like $stmt->store_result(); and then you can unload the mysqli buffer to state a new query.
Hey guys this is a really noob question but for some reason I can't seem to get a single value from a database.
Here is the code that I'm using:
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id")
$stmt->bindParam(':id', $id);
$stmt->execute();
$oldValue = $stmt->fetchColumn();
I do filter the variables before in the code because I got them in this file as post data, here's the code for that part:
$column = filter_input(INPUT_POST, "column", FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_STRING);
$value = filter_input(INPUT_POST, "value", FILTER_SANITIZE_STRING);
In this same file updating the database works so its probably not a problem with connecting to the database. Please help! Thanks
Full error from $stmt:
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 'column FROM teacher WHERE id = ?' at line 1' in /var/www/duties/testTableDataUpload.php:25Stack trace:#0 /var/www/duties/testTableDataUpload.php(25): PDO->prepare('SELECT column F...')#1 {main} thrown in /var/www/duties/testTableDataUpload.php on line 25
I know this is not an answer, just trying to post code to OP.
jquery:
var data="id="+id;
$.ajax({
type:"POST",
data: data,
url:"somePHPdbPage.php",
success: function(result){
$('#blah').html(result);
}
});
Then somewhere on your main page do:
<div id='blah'></div>
what this will do is add the result to the div blah. and you should plainly see it on your main page. then c/p all you want. Have to head out for a bit. will check back in.
and on your php page:
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id")
$stmt->bindParam(':id', $id);
$stmt->execute();
print_r($stmt->errorInfo());
column is a reserved word in MySQL and must be escaped using '`'. You are also missing a semicolon at the end of the line. Try the following:
$stmt = $pdo->prepare("SELECT `column` FROM teacher WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$oldValue = $stmt->fetch();
maybe the problem be with your data but if there be duplicated data you can use one of the belows:
$stmt = $pdo->prepare("SELECT distinct column FROM teacher WHERE id = :id")
or
$stmt = $pdo->prepare("SELECT column FROM teacher WHERE id = :id limit 1")
If you have a column in the teach tabled named 'first_name' you should be able to do the following
$stmt = $pdo->prepare("SELECT first_name FROM teacher WHERE id = :id ORDER BY id DESC limit 1")
$stmt->bindParam(':id', $id);
$stmt->execute();
$row = $stmt->fetch(PDO:FETCH_ASSOC);
echo $row['first_name']; //Will print out the first name (if that is a column in your table of course)
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);