Why is my PDO not working? - php

I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>

You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).

First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>

Why not ask PHP?
catch(Exception $e)
{
die($e);
}

Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);

Related

PDO and query troubleshoot - basic

I am converting an old php 5.6 code to 7.2 and learning how to use PDO.
I have reached a point where I got stuck and would like to learn from the community.
I created a test file structure:
db.php:
<?php
try {
$conn = new PDO($initlocation, $username, $pwdata);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "worked"; // THIS WORKS ON THE SCREEN
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
test.php:
<?php
include("db.php");
$user_query='SELECT * FROM `users` WHERE `email`="user1.a#gmail.com"';
echo $user_query; // I GET THE QUERY PRINTED ON THE SCREEN
echo is_object($conn); // THIS IS 1 WHICH IS GOD
echo "<br>";
echo is_object($res); // THIS IS 1 WHICH IS ODD
try{
$res = $conn->query($user_query);
}
catch (Exception $e){
echo "Query failed: " . $e->getMessage(); // NOTHING
}
echo "<br>";
echo is_object($res); // NOTHING
$data_exists = $res->fetch();
if ($data_exists==1) echo "yes"; // NOTHING
?>
I have left the testing method in the code as well and I am keen to find a better solution to find out why the query does not show anything.
The aim would be to find the email address in the DB and give me some feedback about it. Thank you in advance all the comments I will only learn form them.
Additional info:
When I run the SQL query in the DB directly it does give me the record that has the same email.
Try the following and use prepared statements like protection from SQL injections.
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

PDO PHP select distinct query not working for mssql

I've got a website that is pulling data from my MSSQL Server. I am using functions to build tables for reports. Here's what I've got:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->query($StateSelectSQL);
var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong";
die(print_r($e->getMessage()));
}
I tried this too:
try{
$StateSelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null";
var_dump($StateSelectSQL);echo " What!<br>";
$getSelect = $conn->prepare($StateSelectSQL);
$getSelect->execute();
//$getSelect = $conn->query($StateSelectSQL);
//var_dump($getSelect);echo " When!<br>";
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
var_dump($StateSelectNames);echo " Where!<br>";
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}
The second and third var_dump's never show anything and the rest of the code (not shown here) doesn't get run. If I comment out the $getSelect and $StateSelectNames lines (with the var_dump's under them) then everything else works.
Here is my DBConn.php file that is included above the Function:
$conn = new PDO("sqlsrv:server=$servername;database=$dbname", $username,$password);
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::SQLSRV_ATTR_QUERY_TIMEOUT, 10);
What is wrong with the line $getSelect = $conn->query($StateSelectSQL); I can't figure it out. I tried using it later in my foreach like this:
foreach($conn->query($StateSelectSQL) as $StateName)
But that doesn't work either. It again stops at this line and doesn't go any further. The only thing I can think of is that my SQL is messed up, but when I run it in SSMS it works fine!
What's going on?
Try preparing and executing your SQL before using fetchAll. Also consider enabling exception mode if you haven't already and wrapping your statement in a try catch - this should flag any issues (e.g. your applications database user not having permission to access the schema, or syntax error etc)
Exceptions:
See this stack overflow post for info about how to enable
And for your code:
try {
$sql = "
SELECT DISTINCT State
FROM pmdb.MaterialTracking
WHERE State IS NOT NULL
";
$sth = $conn->prepare($sql);
$sth->execute();
$rowset = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($rowset);
} catch PDOException($err) {
echo "Something went wrong".
echo $err;
}
I have figured it out after pulling my hair out all day! I had to include my DBConn.php inside the function. After this it worked. I don't know why that mattered since it is included at the beginning of the file. If there is anyone who can explain why that is i'd be grateful!
It now looks like this:
function BeginTable($rowCount,$headings,$searchValue,$ReportName,$OneButton,$NewSearch)
{
try{
include("DBConn.php");
$SelectSQL = "select distinct State from pmdb.MaterialTracking where State is not null order by State";
$getSelect = $conn->prepare($SelectSQL);
$getSelect->execute();
$StateSelectNames = $getSelect->fetchALL(PDO::FETCH_ASSOC);
}
catch(Exception $e)
{
echo "Something went wrong<br>";
die( print_r( $e->getMessage()));
}

Connecting to MYSQL using php

I am trying to connect to MYSQL using php, but when I use the following command:
$link=mysql_connect("localhost","root","password");
and echo $link, it gives me Resource id #98. What does this mean? Am I not connected?
Okay, I guess it sounds like the connection is okay. Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?
<?php
$conn=new mysqli("localhost","root","password","database");
$sql="INSERT INTO chat_active (user, time)
VALUES('John', '1234')";
?>
What makes you think you are not connected?
According to the docs, mysql_connect()
[r]eturns a MySQL link identifier on success or FALSE on failure.
Since it did not return FALSE, but rather a resource identifier, that means the connection was successful.
Also note that the mysql extension is deprecated since PHP 5.5.0 as MortimerCat pointed out. Instead you should look into the MySQLi or the PDO extension.
"Now, with the following code, I am not seeing any changes in the mysql database. Why could that be?"
As per your edit which you are now using mysqli_ to connect with, and that you're saying that you're not seeing any changes in your database, is because:
You're not passing the DB connection to your query and it is required when using mysqli_.
Rewrite, with a few more goodies:
<?php
$conn=new mysqli("localhost","root","password","database");
// Check if you've any errors when trying to access DB
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
$sql="INSERT INTO chat_active (user, time) VALUES ('John', '1234')";
$result = $conn->query($sql);
// Check if you've any errors when trying to enter data in DB
if (!$result)
{
throw new Exception($conn->error);
}
else{
echo "Success";
}
Read the manual http://php.net/manual/en/mysqli.query.php
Once you've grasped that, get to know mysqli with prepared statements, or PDO with prepared statements, they're much safer.
References:
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/language.exceptions.php
Footnotes:
Your column names user, time suggests that you're trying to enter a string and what appears to be and to be intended as "time" and that the user column is set to varchar.
Make sure that you haven't setup your time column other than a datetime-related type, otherwise MySQL may complain about that.
MySQL stores dates as YYYY-mm-dd as an example.
Visit https://dev.mysql.com/doc/refman/5.0/en/datetime.html in regards to different date/time functions you can use.
MySQL references:
https://dev.mysql.com/doc/refman/5.0/en/char.html
https://dev.mysql.com/doc/refman/5.0/en/data-types.html
https://dev.mysql.com/doc/refman/5.0/en/datetime.html
You yould use mysqli or PDO.
Here's a connection example with PDO:
<?php
$dbuser = 'user';
$dbpasswd = 'passwd';
$dbname = 'dbname';
try {
$gbd = new PDO("mysql:host=localhost;dbname=$dbname;charset=utf8", $dbuser, $dbpasswd);
$gbd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
}
PDO CRUD examples:
//INSERT
try {
$sentence = $gbd->prepare("INSERT INTO table (param1, param2) VALUES (:param1, :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//SELECT
try {
$sentence = $gbd->prepare("SELECT param1,param2 FROM table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
while ($row = $sentence->fetch(PDO::FETCH_ASSOC)){ //Also available FETCH_NUM,FETCH_BOTH AND OTHERS
$result['param1'] = $row['param1'];
$result['param2'] = $row['param2'];
}
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//UPDATE
try {
$sentence = $gbd->prepare("UPDATE table SET param1 = :param1, param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
//DELETE
try {
$sentence = $gbd->prepare("DELETE table WHERE param1 = :param1 AND param2 = :param2)");
$sentence->bindParam(':param1', $param1);
$sentence->bindParam(':param2', $param2);
$sentence->execute();
}
catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
And here's PDO manual
http://php.net/manual/en/book.pdo.php
u are not executing that query.u are only declaring that query.
for execution do--
$conn->query($qry);
it will,execute ur query.

How to Get Error Details From MySQL Stored Procedure

I am calling a mysql stored procedure using PDO in PHP
try {
$conn = new PDO("mysql:host=$host_db; dbname=$name_db", $user_db, $pass_db);
$stmt = $conn->prepare('CALL sp_user(?,?,#user_id,#product_id)');
$stmt->execute(array("user2", "product2"));
$stmt->setFetchMode(PDO::FETCH_COLUMN, 0);
$errors = $stmt->errorInfo();
if($errors){
echo $errors[2];
}else{
/*Do rest*/
}
}catch(PDOException $e) {
echo "Error : ".$e->getMessage();
}
that return below error because the name of the field in insert query was given wrong
Unknown column 'name1' in 'field list'
So i want to know if this is possible to get detailed error information something like:-
Unknown column 'Tablename.name1' in the 'field list';
that could tell me what column of which table is Unknown.
while creating the pdo connection, pass options like error mode and encoding:
The PDO system consists of 3 classes: PDO, PDOStatement & PDOException. The PDOException class is what you need for error handling.
Here is an example:
try
{
// use the appropriate values …
$pdo = new PDO($dsn, $login, $password);
// any occurring errors wil be thrown as PDOException
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$ps = $pdo->prepare("SELECT `name` FROM `fruits` WHERE `type` = ?");
$ps->bindValue(1, $_GET['type']);
$ps->execute();
$ps->setFetchMode(PDO::FETCH_COLUMN, 0);
$text = "";
foreach ($ps as $row)
{
$text .= $row . "<br>";
}
// a function or method would use a return instead
echo $text;
} catch (Exception $e) {
// apologise
echo '<p class="error">Oops, we have encountered a problem, but we will deal with it. Promised.</p>';
// notify admin
send_error_mail($e->getMessage());
}
// any code that follows here will be executed
I found this to be helpful for me. "error_log" prints to the php error log but you can replace with whatever way you'd like to display the error.
} catch (PDOException $ex){
error_log("MYSQL_ERROR"); //This reminds me what kind of error this actually is
error_log($ex->getTraceAsString()); // will show the php file line (and parameter
// values) so you can figure out which
// query/values caused it
error_log($ex->getMessage()); // will show the actual MYSQL query error
// e.g. constraint issue
}
p.s. I know this is a bit late but maybe it can help someone.

PHP PDO error successful no matter what

I have a problem with my database! Here is my code:
<?php
$host = "/homes/49/jc192699/public_html/dbase";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);
if (!$dbhandle){
echo "Error connecting to database.\n";
}
else{
echo "<br>";
echo "<br>";
echo "Database connection successful!";
}
mysql_select_db($database);
?>
The problem is that it's saying "Database connection successful!" No matter what I do, if I type the address in wrong, it still says successful, when I renamed the database to a database that doesn't exist, it still says successful. I can't see what the problem is here?
If anybody could help me out it would be GREATLY appreciated!
Thank you!
For starters, the PDO constructor throws an exception if there is an error. It does not return false. Check for errors using
try {
$dbhandle = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Secondly, as you are using SQLite, provided your dbase directory is writeable by the script, your connection attempt will create an empty database.
Try this:
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e)
{
/*** real error message prints here ***/
echo $e->getMessage();
}
?>
This is directly taken from here:
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.2

Categories