php mysql retrieving single value from database - php

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)

Related

SELECT from and DELETE the same row in one query

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

MySQL SELECT query returning false when prepared

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

Get duplicate entry error message and use in if statement

I would like to get the error message if a duplicate entry error happened with PDO.
this is the code I use where a duplicate entry is possible because id is a unique key:
$movetotable = $conn->prepare("INSERT INTO `$table` SELECT * FROM `$trashtable` WHERE id = :id");
$movetotable->bindParam(':id', $id, PDO::PARAM_STR);
$movetotable->execute();
I hope it is possible with PHP PDO, I know this: PDO::errorCode() but I simply don't know how to use it in an if statement.
Thanks in advance
$stmt = $conn->prepare("INSERT IGNORE INTO `$table` SELECT * FROM `$trashtable` WHERE id = ?");
$stmt->execute([$id]);
$id = $conn->lastInsertId();
if (!$id) {
echo "a dupe!";
}

PHP - SQL not returning row but works on local server

Im trying to get a row, But it does not return anything on my site, But it works perfectly on local host.
public function GetVote($rel)
{
include 'config.php';
$stmt = $dbh->prepare("SELECT updown FROM user_votes WHERE UID = :id AND rel = :rel");
$stmt->bindParam(":id", $this->id);
$stmt->bindParam(":rel", $rel);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['updown'];
}
Running SQL on phpmyadmin, Site:
Running SQL on phpmyadmin, Local:
I dont know why its saying there is no unique colum, VID is unique and auto-increment.
Table structure:
VID is unique, but your are only SELECTing the updown field. Therefore, phpMyAdmin can't let you edit the data and it produces that warning.
Also, try following query:
SELECT *
FROM `user_votes`
WHERE `UID`='76561197996836099'
AND `rel`='5'
LIMIT 0,30
I've noticed the UID and ref fields are varchar, but you're sending an integer (way to big, btw)...
just try this and tell..any output or not??
public function GetVote($rel)
{
include 'config.php';
$stmt = $dbh->prepare("SELECT * FROM user_votes WHERE rel = :rel");
$stmt->bindParam(":rel", $rel);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return $row['updown'];
}

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