Strange PDO behavior - php

I'm using the following code:
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try {
$stmt = $this->conn->prepare("SELECT id, name FROM images");
if ($stmt->execute()) {
if ($stmt->rowCount() > 0)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else
return NULL;
}
catch(PDOException $e)
{
return $e->getMessage();
}
The code perfectly works, but when I edit my query to:
$stmt = $this->conn->prepare("SELECT id, name, description FROM images");
I obtain an empty result.
Obviously the description field exists. Obviously I tested the new query with PHPMyAdmin.
I found that:
if ($stmt->rowCount() > 0)
is TRUE and I also tried to change the fetclAll to FETCH_BOTH.
Do you have any suggestions?
EDIT: OK, I FOUND THE PROBLEM:
In a record, in the column description there was a "è". If I delete the "è", all is perfectly working. Why this happening?

The Problem was due to an accented letter in a record of the database.
The solution is the use of array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4") to set the character set of the connection to 'UTF-8 MultiByte 4' as follows:
try {
$this->conn = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"));
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
The reason this specific version of UTF-8 is used is explained here.

Related

PDO return success but no data is updated on database

when i try to update a row with PDO function it returned success and when i check database there was no data updated
so i followed this question PDOStatement::execute() returns true but the data is not updated which has answers already but didn't work here is what i did
Below is code i tried
<?php
$Fuid = '105199239598939142575';
sendOT($Fuid);
echo '<br>Below is var_dump() Rsult<br>';
check($Fuid);
function sendOT($Fuid) {
try {
$phone = '6381211774';
$otp = '1234';
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code AND phone=:phone WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->bindParam(':veri_code', $otp, PDO::PARAM_STR);
$stmt2->bindParam(':phone', $phone, PDO::PARAM_STR);
$stmt2->execute();
echo 'Updated succeeded';
} catch (Exception $e) {
echo $e;
}
}
function check($Fuid) {
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
$stmt2 = $conn->prepare("SELECT * FROM members WHERE Fuid=:Fuid");
$stmt2->bindParam(':Fuid', $Fuid, PDO::PARAM_STR);
$stmt2->execute();
$unr = $stmt2->fetch(PDO::FETCH_ASSOC);
var_dump($unr);
}
?>
Output
as per the answer in this question PDOStatement::execute() returns true but the data is not updated may be there is no row with WHERE so i tried with the same WHERE with SELECT query and it showed result.
WHY is my UPDATE query doesn't update in database?
After many tries i managed to update with this query.
$stmt2 = $conn->prepare("UPDATE members SET verification_code=:veri_code, phone=:phone WHERE Fuid=:Fuid");
it worked after removing AND from query using como , in update queries.

PDO Inserts Duplicate Data in MySQL

I have the following code and whenever the function is called it is inserting the data twice.
The php that is calling the class/function:
$add_amenity = new listing;
echo $add_amenity->add_amenity($_POST['name']);
Here is the function:
public function add_amenity($a)
{
try {
$dbh = new PDO("mysql:host=" . db_host . ";dbname=" . db_name . "",db_user,db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbh->prepare("INSERT INTO amenitylist (id,name,icon,isactive) VALUES ('',:a,'','1')");
$q->bindParam(':a', $a);
$q->execute();
$this->_results = $dbh->lastInsertId();
} catch(PDOException $e) {
$this->_results = "ERROR: " . $e->getMessage();
}
}

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

Can I include one pdo connection

Im a just moving to using PDO for my development and I see in most tutorials that the connection is opend for each db query like in Jeffery Ways example below
$id = 5;
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Can I still do a connection in an external file and include it at the top of my page like with previous procedural coding and then do my queries below in the page?
<?php include 'includes/db.php';?>
You probably misunderstood what he says. To open one connection and use it throughout the whole application is not that something you "can" but actually you should.
So - yes, you are doing it right.
Also note that this thing with
try {
...
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
that Jeffery taught you is wrong. Never use a try catch to echo an error message. PHP will handle it better
So, your code should be like this
include 'includes/db.php';
$stmt = $pdo->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
while($row = $stmt->fetch()) {
print_r($row);
}
while db.php has to contain something like this
<?php
$dsn = "mysql:host=localhost;dbname=test;charset=utf8mb4";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $username, $password, $opt);
Also note that when using this PDO object, you have to be aware of the variable scope.
Further reading: https://phpdelusions.net/pdo
The short answer is yes,
if you are farmilier with OOPHP it might be worth creating a wrapper class to help with running queries but just creating the connection in a file and including it will get the job done
in the above example you can put
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
into your db.php and the run the queries
$stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
$stmt->execute(array('id' => $id));
wherever you need.
it may also be worth mentioning that you dont have to use prepared statements with PDO which can speed things up in coding however if you wish to do that i would highly recomend a database wrapper class
non prepared statement
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$query = "
SELECT
col_1,
col_2
FROM
table_1
WHERE
col_3 = " . $conn->quote($_POST['input']); //the quotr is important, it escapes dangerous characters to prevent SQL injection
//this will run the query for an insert this is all thats needed
$statement = $conn->query($query);
//fetch single col
$col = $statement->fetch(PDO::FETCH_ASSOC);
//fetch all collums
$cols = $statement->fetchAll(PDO::FETCH_ASSOC);
the advantage of this way is that you can build up the query SQL in a more simple to follow manner, i should not that i havent tested this code but in theory it should be fine as this is how i do database handling
Edit:
Your Common Sense brings up a good point about the echo 'ERROR: ' . $e->getMessage(); being a bad idea and this is a prime example of why you should NEVER blindly copy and paste code
Yes, example:
db.php
<?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();
}
?>
FROM:
http://www.php.net/manual/en/pdo.error-handling.php
Then just include db.php. I name my connection $PDO, seems more implicit, especially when you are building a prepared statement on that.

Invalid Data Source PHP PDO Mysql

<?php
#require_once('inc/dbc1.php');
$dsn = 'mysql:dbname=dbname;host=somehost;
$user = 'someuser';
$password = 'SomePass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$pdo1 = new PDO($dsn, $user, $password);
$pdo1->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth1 = $pdo1->prepare('SELECT pID, lname, fname FROM Professor ORDER BY pID DESC LIMIT 5;');
$sth1->execute(array());
?>
Throws the error:
Uncaught exception 'PDOException' with message 'invalid data source name' in PDO->__construct('', NULL, NULL) on line 1
Anyone see anything wrong with this?
you have
$dsn = 'mysql:dbname=dbname;host=somehost;
maybe just maybe ...
$dsn = 'mysql:dbname=dbname;host=somehost';
unless this was a mouso when cut-and-pasting the question.

Categories