PDO error when Fetching results - php

I am trying to show results from a simple select statement using PDO
<?php
// Define and perform the SQL SELECT query
include('config.inc');
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "SELECT * FROM usuarios where user = '$user' AND password ='$password'";
$stm = $db->prepare($sql);
$stm->execute();
// here you go:
$users = $stm->fetchAll();
foreach ($users as $row) {
print $row["user"] . "-" . $row["password"] ."<br/>";
}
?>
And the only thing I get is errors like this one:
Undefined index: user in C:\wamp\www\proyect\select.php on line 16
Perhaps is something really simple I might be overlooking in this test, I am working with php 5.3.5.
This is the included file:
<?php
$dsn = 'mysql:host=localhost;dbname=carrito';
$username = 'root';
$password = 'root';
try {
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e){
$error_message = $e->getMessage();
//include('db_error.php');
echo $error_mesage;
file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
exit();
}
?>

If I may guess:
you have PDO::CASE_UPPER set.
http://www.php.net/manual/en/pdo.constants.php
or your column name is just simply upper cased naturally.
But...stop wondering and start investigating. Simply do
var_dump($users);
to see what you have.

Remove:
$users = $stm->fetchAll();
foreach ($users as $row) {
print $row["user"] . "-" . $row["password"] ."<br/>";
}
And try this:
while($row = $stm->fetch(PDO::FETCH_ASSOC)){
print $row["user"] . "-" . $row["password"] ."<br/>";
}

Related

Why does my PDO $stmt->bind_result() function call hang after executing a SELECT query?

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.

Separate connection from PDO

I am new to PDO. I try to understand.
What is the best way to separate the connection from the rest with PDO?
For instance. I have this code that works well:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
It could be useful to have the connection in a separate file. I tried that and it works well but I am not sure if it is the best way to do it. Is it ok to have the try-catch only with the connection?
index.php:
include("includes/connetion.php")
$sql = "SELECT podcast, text
FROM bookmarks
WHERE data = :data";
$statement = $conn->prepare($sql);
$data = 1;
$statement->bindValue(':data', $data);
$statement->execute();
echo $statement->rowCount() . " records SELECTED successfully <br>";
$rows = $statement->fetchAll();
foreach($rows as $row){
echo $row['podcast'] . '<br>';
echo $row['text'] . '<br>';
}
$conn = null;
connection.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "podcast";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// $conn = new PDO("sqlite:/Applications/MAMP/db/sqlite/podcast", $username, $password); //Lite
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully <br>";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I tried that and it works well but I am not sure if it is the best way to do it.
As long as your code is a usual spaghetti as shown above, it's all right with include.
Is it ok to have the try-catch only with the connection?
quite contrary, there shouldn't be a try catch with the connection as well:
"Catch an exception only if you have a handling scenario other than just reporting it. Otherwise just let it bubble up to a site-wide handler (note that you don't have to write one, there is a basic built-in handler in PHP, which is quite good)."
If you are trying to catch possible exception you have to do it everywhere you communicate with database. So you have to wrap try-catch also around code which ask database for some data.
Another step is to separate concepts of getting data from database representing them (sending them to output as you do it). You can check some MVC concept - how to do it.

Using PHP have a MySQL statement into multiple PHP variables

A little backdrop to what I'm trying to accomplish..
I'm making a simple CMS / blog and I'm trying to have the signature auto created from the database's firstname / lastname values by selecting them by the username..
Then after they are selected I am trying to put them into one variable
Example:
$firstname = row['firstname'];
$lastname = row['lastname'];
$signature = $firstname + " " + $lastname;
echo 'Created by: ' . $signature;
The above is what mentally I'm trying to accomplish but I just can't seem to get quite there. This is what I have so far, and I'm not having any luck...
$username = $_SESSION['username'];
$sqlName = "SELECT * FROM users WHERE username = $username";
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$resultName = $connName->query($sqlName);
foreach ($resultName as $row) {
$firstname = $rowN['firstname'];
$lastname = $rowName['lastname'];
}
This is my most current rendition for those wondering:
$username = $_SESSION['username'];
$connName = new PDO('mysql:host=localhost;dbname=platform', 'tyler', 'H011mann');
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlName = "SELECT * FROM users WHERE username = $username";
$resultName = $connName->query($sqlName);
$name = 'Created by : ';
foreach ($resultName as $row) {
$name .= $row['firstname'] . ' ' . $row['lastname'];
}
echo '<div>' . $name. '</div>';
There are some issue with your code. At first glance, I was missing the PDO object. On closer inspection, I've noticed you were using the wrong concatenation operator and you didn't seem to use Prepared Statements either.
Prepared Statements will protect you from SQL injection as well as users using characters that might cause issues for your MySQL database. I've written the following code for you that shoul deal with all your issues. Please make sure to take a look at the comments inside:
<?php
session_start();
//Get Username
$username = $_SESSION['username'];
//MySQL Server Data
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//PDO Object
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
// Set PDO options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instance
try{
$pdo = new PDO($dsn, $dbuser, $dbpass, $options);
}
// Catch any errors
catch(PDOException $e){
print $e->getMessage();
exit;
}
try {
//Setup Query
$sql = "SELECT * FROM users WHERE username = :username";
//Prepare Query
$pdo->prepare($sql);
//Bind Values (to prevent SQL injection)
$pdo->bindParam(':username', $username);
//Execute Query
$pdo->execute();
//Fetch Data
$data = $pdo->fetch(PDO::FETCH_ASSOC);
//Combine results
$signature = $data['firstname']. " " .$data['lastname'];
echo $signature;
} catch (PDOException $e) {
print $e->getMessage();
exit;
}
?>
Try this
$resultName = $connName->query($sqlName);
$signature = 'Created by : ';
foreach ($resultName as $row) {
$signature .= $row['firstname'] . ' ' . $row['lastname'];
}
echo $signature;
$username = $_SESSION['username'];
$sqlName = "SELECT * FROM users WHERE username = $username";
$connName->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$resultName = $connName->query($sqlName);
foreach ($resultName as $row) {
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
$signature=$firstname.' '.$lastname;
Unless your sample code up there was just some form of pseudo code, the concatenation operator in PHP is ".", not "+". Just use that to combine the 2 values returned into a variable:
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$signature = $firstname . ' ' . $lastname;

PHP PDO is not displaying any data on my web page

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

PHP login script always returns "login failed"

I have to give users the ability to log in for an assignment. At first, it seemed to me this script was simple enough to work, but everytime I try to log in with an existing account it gives me the "login failed" message. I don't know where my mistake lies. It's a PostgreSQL database, I'll enclose an image of it below.
<?php
require 'databaseaccess.php';
try {
$conn = new PDO('pgsql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME,DB_PASSWORD);
} catch (PDOException $e) {
print "Error: " . $e->getMessage() . "\n";
phpinfo();
die();
}
$username = $_POST['username'];
$password = $_POST['password'];
$tablename = "users";
// sql-injection counter
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$qry = $conn->prepare("SELECT * FROM $tablename WHERE userid = :username and userpass = :password");
$qry->bindParam(':username', $username, PDO::PARAM_STR, 16);
$qry->bindParam(':password', $password, PDO::PARAM_STR, 16);
$qry->execute();
$result = pg_query($qry);
$count = pg_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($count == 1) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
header("location:logingelukt.php");
} elseif ($count = -1) {
echo "there has been an error";
} else{
print $count;
echo "login failed";
}
?>
I have no problems connecting to the database, so that's not an issue, it's just that it always sees $count as something else than zero. Another oddity is that the print $count command doesn't output anything.I use the account I made with postgresql outside of the page, which is just admin:admin. Also, I'm sure the right variables are getting passed from the form.
EDIT: After using var_dump($result), as advised by kingalligator, it seems that $result is indeed NULL, thus empty. I'm gonna try using fetch() instead of pg_query().
I think the issue is that you're mixing PDO and pg_ functions.
Replace:
$result = pg_query($qry);
$count = pg_num_rows($result);
With:
$result = $qry->fetchAll();
$count = count($result);
PDO Function reference can be found here: http://www.php.net/manual/en/class.pdostatement.php
Have you confirmed that you're actually getting data returned from your query? Try this:
var_dump($result);
To ensure that data is being returned from your query. You can still have a successful connection to a database, yet have a query that returns nothing.
You probably should check your column userid at WHERE clause. I don't know the table columns, but is strange that 'userid' has the name of the user in:
"SELECT * FROM $tablename WHERE userid = :username and userpass = :password"
Maybe it is causing the problem.

Categories