PHP PDO is not displaying any data on my web page - php

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);
}
}
?>

Related

Can't figure out this bindParam issue

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

Failed to select data from PHPMyAdmin using PHP PDO

This is my code:
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
?>
But, when I run it, nothing gets printed. What's wrong?
Yes, my table is not empty. I am 100% able select & print data using MySQLi Object-oriented, but not working with PDO. What's wrong in my code?
Call the function
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
//call the function here
printResult($conn);
?>
To run a function you must call it.
<?php
//Connect to DB
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=users", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// and if this fails there is no point continuing so add an exit
exit;
}
function printResult($conn) {
$sql = 'SELECT name FROM info';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
}
}
printResult($conn); // call the function
?>
You don't call function printResult from anywhere.
Add to your code printResult($conn);

How do I reconnect my web pages on my website after updating to PHP 7 with a MySQL database 5.0.0?<?

I added the i updates to communicate with the database & now the page links don't work.
<?php
// Connect to database
$link=mysqli_connect('localhost', 'xxxxx', 'xxxxx');
mysqli_select_db($link, 'waddellc_PHRDB');
$sql = "SELECT * FROM quotes ORDER BY id";
$result = mysqli_query($link, $sql) or die(mysql_error());
$tenant_quotes = array();
$owner_quotes = array();
while($row = mysqli_fetch_array($result)) {
This should do the work, using PDO :
$servername = "localhost";
$username = "username";
$password = "password123";
$conn = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=databaseName", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
if(!is_null($conn)){
$stmt = $conn->prepare("SELECT * FROM quotes ORDER BY id");
if ($stmt->execute()) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
}
I also think you need to update your database, it's quite old now.

Changing from mysqli to PDO did not work?

I previously used mysqli and now i would like to use PDO instead but I did not echo any result from my database. I have read so many articles about PDO tutorial but they teach different things. I tried to pick piece by piece and came up with this code, but i did not echo any result from my database or throw any error.
try{
$stmt = $conn->query("SELECT * FROM memberpost ORDER BY poststart DESC LIMIT $start_from,$num_rec_per_page");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$row = $stmt->fetch();
if(count($row)>0){
while($row = $stmt->fetch()) {
echo $row['title']."<br>";
}
}
else{
echo "NO result found";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Here is my database connect code:
try {
$conn = new PDO('mysql:host=localhost;dbname=mydatabase;charset=utf8', $username, $password); //new PDO
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Edit your database connection code to this:
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
And try this code in your .php file :
$sth = $conn->prepare(SELECT * FROM memberpost)
$sth->execute();
$red = $sth->fetchAll();
print_r($red);
I found this on the internet, it might help:
// defining query
$sql = 'SELECT name, surname, zip FROM table';
// showing results
foreach($db->query($sql) as $row){
echo $row['name']. '<br>';
echo $row['surname']. '<br>';
echo $row['zip']. '<br>';
}
Source (ita): http://www.mrwebmaster.it/php/guida-utilizzo-pdo_7594_4.html

Login script using PDO extension not working

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

Categories