<?php
require_once('dbconfig.php');
global $con;
$query = $con->prepare("SELECT * FROM userinfo order by id DESC");
$query->execute();
mysqli_stmt_bind_result($query, $id, $name, $username, $password);
You should use ->bindColumn Manual
See also This answer.
Best Practise: Do not use SELECT * instead define each column you need to grab from the table.
Do not globalise your connection variable. This is a security risk as well as adding bloat and should be unneeded on your code.
Because it is a static statement you can use ->query rather than prepare, as nothing needs to be prepared.
Solution:
$query = $con->query("SELECT id,name,username,password FROM userinfo ORDER BY id DESC");
try {
$query->execute();
$query->bindColumn(1, $id);
$query->bindColumn(2, $name);
$query->bindColumn(3, $username);
$query->bindColumn(4, $password);
}
catch (PDOException $ex) {
error_log(print_r($ex,true);
}
Alternatively:
A nice feature of PDO::query() is that it enables you to iterate over the rowset returned by a successfully executed SELECT statement. From the manual
foreach ($conn->query('SELECT id,name,username,password FROM userinfo ORDER BY id DESC') as $row) {
print $row['id'] . " is the ID\n";
print $row['name'] . " is the Name\n";
print $row['username'] . " is the Username\n";
}
See Also:
Mzea Has some good hints on their answer, you should use their $options settings as well as using their suggested utf8mb4 connection character set.
And their suggestion for using ->fetchAll is also completely valid too.
Try this
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
PDO::ATTR_EMULATE_PREPARES => false, // turn off emulation mode for "real" prepared statements
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //turn on errors in the form of exceptions
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, //make the default fetch be an associative array
];
try {
$pdo = new PDO($dsn, "username", "password", $options);
} catch (Exception $e) {
error_log($e->getMessage());
exit('Something weird happened'); //something a user can understand
}
$arr = $pdo->query("SELECT * FROM myTable")->fetchAll(PDO::FETCH_ASSOC);
Related
I am totally confused by mySQLi. Although I have been using procedural mysql calls for years, I want to get used to making prepared statements for the db security/mySQL injection protection it offers. I am trying to write a simple select statement (yes I know making a procedural call for this offers performance enhancement). When run, I get all the echoes until I hit the $result = $stmt->get_result(); component. It all seems fairly straightforward to me, but I am at a loss after hours of reading manuals on mySQLi. Any ideas why this would be failing?
*note: this is a test environment and while no sanitizing/escaping of characters is taking place, I am only passing valid content into the variables $username and $email. And also, I have looked all over SO to find the solution to my issue.
function checkUsernameEmailAvailability($username, $email) {
//Instantiate mysqli connection
#$mysqli = new mysqli(C_HOST,C_USER,C_PASS,C_BASE) or die("Failed to connect to MySQL database...");
if (!$mysqli)
{
echo 'Error: Could not connect to database. Please try again later...';
exit;
} else {
echo 'mysqli created';
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT username,email FROM tb_users WHERE username=? OR email=?")) {
echo '<br />MYSQLi: ';
/* Bind parameters s - string, b - boolean, i - int, etc */
$stmt -> bind_param("ss", $username, $email);
echo '<br />paramsBound...';
/* Execute it */
$stmt -> execute();
echo '<br />Executed';
$result = $stmt->get_result();
echo '<br />Result acquired';
/* now you can fetch the results into an array - NICE */
$myrow = $result->fetch_assoc();
echo '<br />Fetched';
/* Close statement */
/$stmt -> close();
echo '<br />Done mysqli';
}
}
Also, do I have to instantiate a mysqli every time I call a function? I'm assuming they're not persistent db connects like in procedural mysql. Yes, I am aware this is a scope issue, and no I have not been able to understand the scoping of this class variable. When I declared it outside of the function, it was not available when I came into the function.
UPDATE
if I change line 12 from:
if($stmt = $mysqli -> prepare("SELECT username,email FROM tb_users WHERE username=? OR email=?")) {
to:
$stmt = $mysqli->stmt_init();
if($stmt = $mysqli -> prepare("SELECT username,email FROM tb_users WHERE username=? OR email=?")) {
if(!stmt) echo 'Statement prepared'; else echo 'Statement NOT prepared';
I get Statement NOT prepared. Now I'm even more confused....
UPDATE:
I contacted my hosting provider and apparently mySQLi is supported, and the mysqlnd driver is present. Perhaps there is a way to simply test this? Although they usually have given me pretty knowledgeable answers in the past.
UPDATE...AGAIN: I checked my server capabilities myself and discovered, while mysqli and PDO are present, mysqlnd is not. Thusly, I understand why get_result() will not work (mysqlnd required I think), I still don't understand why the prepared statement itself will not work.
Through some checking, even though mysqli is installed on my host, apparently the mysqlnd driver is not present. Therefore, get_result() can not be used(php manual defines get_result as mysqlnd dependent), and instead extra coding would need to be done to handle my result the way I would like.
Therefore, I decided to try and learn how PDO works, and within minutes, voila!!!
Replaced the above code with this:
function checkUsernameEmailAvailability($username, $email) {
echo 'pdo about to be created';
$dsn = 'mysql:dbname='.C_BASE.';host='.C_HOST;
$user = C_USER;
$password = C_PASS;
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$params = array(':username' => $username, ':email' => $email);
try{
$sth = $dbh->prepare('SELECT username,email FROM tb_users WHERE username = :username OR email = :email ');
} catch(PDOException $e) {
echo 'Prepare failed: ' . $e->getMessage();
}
try{
$sth->execute($params);
} catch(PDOException $e) {
echo 'Execute failed: ' . $e->getMessage();
}
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
}
As much error checking as I could think of, and no problems at all first crack at it!
Final Code
function checkUsernameEmailAvailability($username, $email) {
$dsn = 'mysql:dbname='.C_BASE.';host='.C_HOST;
$user = C_USER;
$password = C_PASS;
new PDO($dsn, $user, $password);
$params = array(':username' => $username, ':email' => $email);
$sth = $dbh->prepare('SELECT username,email FROM tb_users WHERE username = :username OR email = :email ');
$sth->execute($params);
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
}
mysqli_stmt :: get_result is Available only with mysqlnd package. remove php5-mysql package and install php5-mysqlnd instead
I was using mysqli_fetch_array and the counting was right until I changed to fetch(), which now only returns the total number of rows instead of returning each number for each row.
So for row one, I want to echo "1", and so on.
NEW NOTE :Everything else inside the while statement is returning correct values, except the counter which returns the total number of rows whereas I want a row number in the order that it was selected from the sql statement.
As requested. This is my connection.
I don't know if i'm suppose to be checking " $e->getMessage();" on every query since I'm using this connection for all my queries.
try {
$dbh = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'usr', 'pwd',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
} catch (PDOException $e){
echo $e->getMessage();
}
This worked
$query = mysqli_query($con, 'SELECT * FROM music');
$count = 0;
while($row = mysqli_fetch_array($query)){
$count++;
echo $count;
}
The new doesn't work.
$query = $dbh->query('SELECT * FROM music');
$count = 0;
while($row = $query->fetch()){
$count++;
echo $count;
}
Works fine, use a try catch do see if your PDO connection is working.
try {
$dbh = new PDO('mysql:host=localhost;dbname=db', 'root', 'root',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql = 'SELECT * FROM music';
$sth = $dbh->query($sql);
$count = 0;
while($row = $sth->fetch()){
$count++;
echo $count;
}
I've just tested this and it works fine. Either your PDO connection is incorrect or your query returns no results. I suggest you var_dump($dbh) and see if it returns a PDO object or check that your query is correct. Is your table called music? It is case sensitive.
You also need to change your connection form mysqli to PDO
$mysqli = new mysqli("localhost", "user", "password", "database");
to
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password');
You can also throw PDO exceptions to see if any are occuring:
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
$conn->exec("SET CHARACTER SET utf8");
http://coursesweb.net/php-mysql/pdo-select-query-fetch
What about:
if ($pdo){
$query=$pdo->prepare("SELECT count(*) as cnt FROM music");
if($query->execute()){
$count = $query->fetch()[0];//or fetch()['cnt']
echo $count;
}
}
PDO have a little different behavior. This is a replacement for your mysqli.
try {
$dbh = new PDO('mysql:host=localhost;dbname=database', 'user', 'password',array(
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// optional
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
));
$count = 0;
foreach ($dbh->query("SELECT * FROM `music`") as $row) {
$count++;
echo $count;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
exit();
}
I hope that helped.
Try using PDO::FETCH_NUM to get the row count directly :-
$countquery = $dbh->query('SELECT COUNT(1) FROM music');
$rowCount = 0;
$rowCount = $countquery ->fetch(PDO::FETCH_NUM);
echo $rowCount;
//And then do another query for the real data if need be
* This makes use of a query to get the row count, and saves you the time taken by the while loop.
I'm using PDO for my querys and try to escape some '&' since they make the request invalid. I already tried with mysql_real_escape_string and pdo quote... both didn't escaped the '&'. My values are for example "James & Jack".
As Connector:
$this->connect = new PDO("mysql:host=$db_host;dbname=$db_name;", $db_user, $db_pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
As Query:
function check_exist($query,$parameter)
{
try
{
$this->connect->prepare($query);
$this->connect->bindParam(':parameter', $parameter, PDO::PARAM_STR);
$this->connect->execute();
return $this->connect->fetchColumn();
unset ($query);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Finaly the Call to action
$db = new database;
$db->connect('framework','localhost','root','');
$result = $db->check_exist('SELECT COUNT(*) FROM cat_merge WHERE cat=:parameter',$cat);
Try using prepared statements this way:
<?php
// Connect to the database
$db = new PDO('mysql:host=127.0.0.1;dbname=DB_NAME_HERE', 'username', 'password');
// Don't emulate prepared statements, use the real ones
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// Prepare the query
$query = $db->prepare('SELECT * FROM foo WHERE id = ?');
// Execute the query
$query->execute($_GET['id']);
// Get the result as an associative array
$result = $query->fetchAll(PDO::FETCH_ASSOC);
// Output the result
print_r($result);
?>
I am using PDO for the first time.
$result=$dbh->query($query) or die($dbh->errorinfo()."\n");
echo $result->fetchColumn();
$row = $result->fetch(PDO::FETCH_ASSOC);
The result of following code is that $row is initilazed ie isset but is empty.
I couldnot get where did I go wrong. thanks in advance
PDO doesn't do the old mysql_* style do or die() code.
Here's the correct syntax:
try {
//Instantiate PDO connection
$dbh = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
//Make PDO errors to throw exceptions, which are easier to handle
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Make PDO to not emulate prepares, which adds to security
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = "SELECT * FROM `some_table`";
//Prepare the statement
$stmt = $dbh->prepare($query);
//Execute it (if you had any variables, you would bind them here)
$stmt->execute();
//Work with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//Do stuff with $row
}
}
catch (PDOException $e) {
//Catch any PDOExceptions that were thrown during the operation
die("An error has occurred in the database: " . $e->getMessage());
}
You should read the PDO Manual, to get better understanding of the subject.
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 7 years ago.
I'm trying to work with PDO class on php but I have some trouble to find the right way to handle errors, I've wrote this code:
<?php
// $connection alreay created on a class which works with similar UPDATE statements
// I've simply added here trim() and PDO::PARAM... data type
$id = 33;
$name = "Mario Bros.";
$url = "http://nintendo.com";
$country = "jp";
try {
$sql = "UPDATE table_users SET name = :name, url = :url, country = :country WHERE user_id = :user_id";
$statement = $connection->prepare ($sql);
$statement->bindParam (':user_id', trim($id), PDO::PARAM_INT);
$statement->bindParam (':name', trim($name), PDO::PARAM_STR);
$statement->bindParam (':url', trim($url), PDO::PARAM_STR);
$statement->bindParam (':country', trim($country), PDO::PARAM_STR, 2);
$status = $statement->execute ();
} catch (PDOException $e) {
print $e->getMessage ();
}
print $status; // it returns a null value, and no errors are reported
?>
this portion of code doesn't report errors, but it simply doesn't work, the var $status at the bottom, return a null value.
can someone help me to find where I'm wrong?
PDO won't throw exceptions unless you tell it to. Have you run:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
on the PDO object?
You can add the attribute one time while you connect you mysql.
function connect($dsn, $user, $password){
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
}
Thanks