I'm trying to fetch some data from a MySql db using PDO but no matter what I do, I can't get anything when using a prepared statement... please tell me what I'm doing wrong.
The following code runs but returns nothing.
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR WHERE uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
foreach ($query as $row) {
print_r($query);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}
What Alive To Die wrote was correct, and there was also an extra WHERE in the SQL string which also messed up the answer, this is the final code:
try {
$dbh = new PDO('mysql:host=localhost;dbname=banim', 'root', '');
$uName = "banim"; //$_POST['uName'];
$email = "Rabak#gmail.com"; //$_POST['email'];
$query = $dbh->prepare("SELECT * from users WHERE email = :email OR uName = :name");
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->bindParam(":name", $uName);
$query->bindParam(":email", $email);
$query->execute();
while($row = $query->fetch()){
print_r($row);
}
} catch (PDOException $e) {
echo "PDOException: " . $e->getMssage() . PHP_EOL;
}
Related
I have a MySQL database with table "Test" that has one column "TestData". There are three records with the following values for TestData: "This is value 1", "Here is another string", and
"Third just for luck".
I wrote the following PHP code to retrieve the records.
<?php
try {
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new PDO("mysql: host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT TestData FROM Test";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
catch(PDOException $e)
{
$finalResult = $finalResult . "," . $e->getMessage();
}
echo "you are here (" . $stmt->rowCount() . ")<br>";
if ($stmt->rowCount() > 0) {
echo "found (" . $stmt->rowCount() . ")<br>";
$stmt->bind_result($td);
echo "bind successful<br>";
while ($stmt->fetch()) {
echo "testdata (" . $td . ")<br>";
}
} else {
echo "nothing found<br>";
}
?>
The result I receive is
you are here (3)
found (3)
The PHP script never gets to the "echo 'bind successful'" statement. The "$stmt->bind_result($td);" statement hangs.
The query appears to work, given that rowCount = 3. I've used essentially the same structure to perform INSERTS that work properly.
What's wrong with what I'm doing? Thanks.
I changed my code to the following and it works.
<?php
$hostname = "redacted";
$username = "redacted";
$password = "redacted";
$database = "redacted";
$conn = new mysqli($hostname, $username, $password, $database);
if ($conn->connect_error) {
fwrite(STDERR, "Connection failed: " . $conn->connect_error . "\n");
exit(1);
}
$sql = "SELECT TestData FROM Test WHERE ?";
$stmt = $conn->stmt_init();
if(!$stmt->prepare($sql)) {
print "Failed to prepare statement\n";
} else {
$stmt->bind_param("s", $condition);
}
$condition = "1 = 1";
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
echo "testdata(" . $r . ")<br>";
}
}
?>
No more mixing PDO and MySQLi for me. Thanks for the help. Sorry for the inconvenience.
If you are just trying to get the items from the database using php pdo you need to store the results.
$results = $stmt->fetch(); //will get one row
$results = $stmt->fetchAll(); //will take all results and store in an array
hope this helps.
I've recently tried to convert my procedural MySQL queries to PDO statements. I've copied the following code from php official documentation and added my parameters to it. It is not showing any results in the page.
<?php
$dsn = 'mysql:host=localhost;dbname=database';
$user = 'user';
$pass = 'pass';
try {
$dbh = new PDO($dsn , $user, $pass);
$dbh = null;
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" . $e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where username = ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
?>
Try this:-
<?php
$dsn = 'mysql:host=localhost;dbname=databasename';
$user = 'user';
$pass = 'password';
try {
$dbh = new PDO($dsn , $user, $pass);
} catch (PDOException $e) {
print "An error has occurred. Please contact support. <br/>" .
$e->getMessage() . "<br/>";
die();
}
$value = 'user1';
$stmt = $dbh->prepare("SELECT * FROM table where column= ?");
if ($stmt->execute(array($value))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
I have chat that uses long polling to get messages from DB (there are no problems to load them). But i also have script that insert messages into DB and it sometimes doesnt work ... it just doesn´t insert the row but it says that it was inserted.
<?php
include_once "../conect.php";
$sprava = $_POST['sprava']; // received message
session_start();
echo $sprava;
$ja = $_SESSION['id'];
session_write_close();
$cas = time();
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
if ($stmt->execute()) echo "works ";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
echo $on;
if ($on == "") return 0;
try {
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) echo " works";
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();}
?>
i get no errors and outpus is still in form as it should be
for example
1 works 37 works
2 works 37 works
3 works 37 works
4 works 37 works
5 works 37 works
that first number is message I entered, the first "works" means that ID of user was loaded, the second nuber is loaded ID and the last "works" means that the message was inserted into DB but it sometimes wasn´t (just sometimes).
but in DB i have rows only with for example
1
2
4
and 3, 5 is missing
An INSTEAD OF INSERT trigger is doing this. Check your table's triggers.
You are returning 0 when $on is empty, when this happens , it won't insert the data
If you are going to SELECT an INSERT in the same script, then I suggest you to split that logic especially if the INSERT depend on what the SELECT returns.
Create 2 fucntions:
SELECT function
function select_som($conn, $ja){
try {
$query = "SELECT som FROM user WHERE id = :ja";
$stmt = $conn->prepare($query);
$stmt->bindValue(':ja', $ja, PDO::PARAM_STR);
$success = $stmt->execute();
if(!$success){
echo "SELECT failed";
}
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$on = $row["som"];
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $on;
}
INSERT function
function insert_data($conn, $cas, $sprava, $ja, $on){
try {
$query = "INSERT INTO chat (cas,text,od,pre) VALUES (:cas, :text, :od, :pre)";
$stmt = $conn->prepare($query);
$stmt->bindValue(':cas', $cas, PDO::PARAM_STR);
$stmt->bindValue(':text', $sprava, PDO::PARAM_STR);
$stmt->bindValue(':od', $ja, PDO::PARAM_STR);
$stmt->bindValue(':pre', $on, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount();
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
return $affected_rows;
}
Usage:
if(isset($_POST['sprava'])){
include_once "../conect.php";
//session
session_start();
$ja = $_SESSION['id'];
session_write_close();
//connection
$conn = new PDO($databaza, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//get "$on"
$on = select_som($conn, $ja);
//insert
if($on != ""){
$cas = time();
$sprava = $_POST['sprava'];
$success = insert_data($conn, $cas, $sprava, $ja, $on);
if($success==1){
echo "INSERT Successful";
}else{
echo "INSERT Failed!!";
}
}else{
echo "on is empty, cannot insert data";
}
}
I try to make a secure method that checks if a username or email is not taken and I'm not sure if this is the right way. How can I do this better?
private function checkAvailability() {
try {
$conn = new PDO(DB_SERVER, DB_USER, DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = ("SELECT COUNT(*) FROM users WHERE username = :username OR email = :email");
$st = $conn->prepare($sql);
$st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
$st->bindValue(":email", $_POST["email"], PDO::PARAM_STR);
$st->execute();
if($st->fetchColumn() > 0) {
$sql = ("SELECT COUNT(*) FROM users WHERE username = :username");
$st = $conn->prepare($sql);
$st->bindValue(":username", $_POST["username"], PDO::PARAM_STR);
$st->execute();
if($st->fetchColumn() > 0) {
throw new Exception("That username is already taken");
} else {
throw new Exception("That e-mail is already registered.")
}
return 0;
} else {
return 1;
}
$conn = null;
} catch (PDOException $e) {
echo "Database error: " . $e->geMessage();
} catch (Exception $e) {
echo "Registration failed: " . $e->geMessage();
}
}
public function registerUser() {
if(self::checkAvailability) {
// register user
}
}
You are already on the right path here.
The query SELECT COUNT(*) FROM users WHERE username = :username OR email = :email can be a performance problem, because the db can't use any index here. So you might want to split that in two statements one for username and one for email. That would also help you determining which error occured.
Also you don't need every hit in the db just the first, so a limit 1 is also usefull.
I am unsure if I am doing it properly but I just started working with PDO and I am not able to get my code to work. I continue to get the error "sorry could not connect" and I am unable to figure out what is wrong.
Included below is the code that I am using:
function doRun( $data )
{
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare(' SELECT
username, pass
FROM
testTable
WHERE
username = :name
AND
pass = :pass
');
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
$stmt->execute();
//$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$result = $stmt->fetchColumn();
if($result == false)
{
echo 'sorry could not connect';
}
else
{
$_SESSION['username'] = $user;
echo 'logged in as' . $user;
}
}
catch (PDOException $e)
{
echo "throw";
}
$db = NULL;
}
This would give you 0 rows as it seems that $username and $pass are not defined:
$stmt->bindParam(':name', $username, PDO::PARAM_STR);
$stmt->bindParam(':pass', $pass, PDO::PARAM_STR);
^^^^^^^^^
You probably want some elements from $data variable you are feeding to the function as a username and password.
Later on you are using a variable $user that is undefined as well.
What does $data contain?
The reason that you are "unable to connect", even though you are connecting but you're not finding a match, is because your user variables are not defined.
Try the following solution:
<?php
function doRun( $data )
{
$msg = '';
$username = isset($_POST['name']);
$pass = isset($_POST['pass']);
try
{
$db = new PDO('mysql:host=localhost;dbname=testData', 'root', 'root');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare('
select
username
,pass
from
testTable
where
username = :name
and pass = :pass
');
$stmt->execute(array(':name' => $username, ':pass' => $pass);
$result = $stmt->fetchAll();
if(!empty($result)){
$_SESSION['username'] = $user;
$msg = "logged in as $user";
}else{
$msg = "Unable to connect";
}
} catch (PDOException $e) {
echo "Error: $e";
}
echo $msg
$db = NULL;
}
?>