PostgreSQL in PDO never gives error - php

I have this code:
$host = "127.0.0.1";
$db = "mydb";
$user = "user";
$pass = "pass";
$dbh = new PDO("pgsql:dbname=$db;host=$host", $user, $pass);
$query = "select * from mytable";
$stmt = $dbh->prepare($query);
if ($stmt) {
echo "Query was OK, execute!";
$stmt->execute();
var_dump($stmt->fetchAll());
} else {
echo "Query was NOT OK!";
var_dump($dbh->errorInfo());
}
but it always says
Query was OK, execute
even if the SQL is blatantly wrong (e.g. "bogus SQL" or querying a non-existing table). It always returns a dataset, which is empty when the query is wrong. I know the connection is fine, because a valid query returns valid results.
I do not see any errors anywhere, also not in the logs.

According to the documentation:
Note:
Emulated prepared statements does not communicate with the database server so PDO::prepare() does not check the statement.
So you can write whatever to be prepared, only executing it will check it for validity if emulation is on.
You also don't check the return value of execute() to see if it succeeded and fetchAll() returns an empty array if there are no results by documentation.

According to the documentation:
Note:
Emulated prepared statements does not communicate with the database
server so PDO::prepare() does not check the statement.
So you can write whatever to be prepared, only executing it will check it for validity if emulation is on.
If you want to try if there is any error, you have to excute it then check if the previous was excuted.
$stmt->execute();
if($stmt->errorCode() === '00000'){
// Mean "OK"
var_dump($stmt->fetchAll());
} else {
echo "Query was NOT OK!";
var_dump($dbh->errorInfo());
}

Related

Hide comments for all blocked friends

Here is the code for blocking comments from blocked users. Comments are getting blocked for only the first blocked user in the database table, but i want the comments to be hidden for all the blocked users in database table.
<?php
include_once('adminpanel/dbconnect.php');
$sql_query =mysql_query("SELECT * FROM blocked_accounts WHERE
blocker_id=".$id);
$rr=mysql_fetch_array($sql_query);
if($rr['blocked_id'] == $r['id'] && $rr['blocker_id'] == $id)
{
echo "";
}
else
{ ?>
You need to go through all the records and if any of them match, then this is blocked. This code first sets a flag to say it isn't blocked, then if any of the records match, sets this to true and breaks out of the loop (not worth carrying on)...
<?php
include_once('adminpanel/dbconnect.php');
$sql_query = $conn->prepare( "SELECT * FROM blocked_accounts WHERE
blocker_id= ?");
$sql_query->bind_param("i", $id);
$sql_query->execute();
$blocked = false;
while ($rr=mysqli_fetch_assoc($sql_query)) {
if($rr['blocked_id'] == $r['id'] && $rr['blocker_id'] == $id)
{
$blocked = true;
break;
}
}
if($blocked)
{
echo "";
}
else
{ ?>
As mentioned in the comments, this is update to mysqli_ and prepared statements, you will need to change your connect to use mysqli as well (PHP mysqli connect function may helpd if you are not sure).
Using mysql_* functions is very bad practice because they have been outdated for many years. Since you're in the phase of learning, it's best to focus on learning how to use prepared statements, whether in the form of mysqli or PDO and stick with that.
As to the problem at hand, the code you've given is vague and things that are needed to send the query, such as the connection, are missing. Therefore, my answer aims to guide you into using mysqli prepared statements correctly rather than give you a full-fledged solution.
Code:
<?php
# Establish a connection to the database.
$connection = new mysqli("your host", "your username", "your password", "your db");
# Create a mysqli query.
$query = "SELECT * FROM `blocked_accounts` WHERE `blocker_id` = ?";
# Prepare the query and check whether the operation was successful.
if ($stmt = $connection -> prepare($query)) {
# Bind the parameters to the statement.
$stmt -> bind_param("i", $id); # 'i' means integer
# Execute the statement and check whether the operation was successful.
if ($stmt -> execute()) {
# Get the result out of the statement and cache it.
$result = $stmt -> get_result();
# Close the statement.
$stmt -> close();
# Fetch the first row (use 'while' if you want more).
if ($row = $result -> fetch_assoc()) {
# Check whether the user is blocked...
}
}
}
# Shut down the database connection.
$connection -> close();
?>
Notes:
When you're trying to query the database, remember to use the actual connection you established. In your mysql_query function call, there is not connection passed.
The part && $rr['blocker_id'] == $id in your if check is redundant because the value of $id is the value we used to filter the results returned by the database, so it will be always true.

Grabbing things from database using functions. Is this safe?

I have a simple question. I'm not too good at programming yet but is this safe and correct?
Currently I am using functions to grab the username, avatars, etc.
Looks like this:
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
config.php ^^
function getUsername($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT username FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$name = $stmt->fetch();
return $name["username"];
}
function getProfilePicture($userid) {
require "config/config.php";
$stmt = $conn->prepare("SELECT profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$image = $stmt->fetch();
return $image["profilepicture"];
}
Is this correct and even more important, is this safe?
Yes, it's safe with respect to SQL injections.
Some other answers are getting off topic into XSS protection, but the code you show doesn't echo anything, it just fetches from the database and returns values from functions. I recommend against pre-escaping values as you return them from functions, because it's not certain that you'll be calling that function with the intention of echoing the result to an HTML response.
It's unnecessary to use is_int() because MySQL will automatically cast to an integer when you use a parameter in a numeric context. A non-numeric string is interpreted as zero. In other words, the following predicates give the same results.
WHERE id = 0
WHERE id = '0'
WHERE id = 'banana'
I recommend against connecting to the database in every function. MySQL's connection code is fairly quick (especially compared to some other RDBMS), but it's still wasteful to make a new connection for every SQL query. Instead, connect to the database once and pass the connection to the function.
When you connect to your database, you catch the exception and echo an error, but then your code is allowed to continue as if the connection succeeded. Instead, you should make your script die if there's a problem. Also, don't output the system error message to users, since they can't do anything with that information and it might reveal too much about your code. Log the error for your own troubleshooting, but output something more general.
You may also consider defining a function for your connection, and a class for your user. Here's an example, although I have not tested it:
function dbConnect() {
try {
$conn = new PDO("mysql:host=". $mysql_host .";dbname=" . $mysql_db ."", $mysql_username, $mysql_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e)
{
error_log("PDO connection failed: " . $e->getMessage());
die("Application failure, please contact administrator");
}
}
class User {
protected $row;
public function __construct($userid) {
global $conn;
if (!isset($conn)) {
$conn = dbConnect();
}
$stmt = $conn->prepare("SELECT username, profilepicture FROM accounts WHERE id = ? LIMIT 1");
$stmt->execute([$userid]);
$this->row = $stmt->fetch(PDO::FETCH_ASSOC);
}
function getUsername() {
return $this->row["username"]
}
function getProfilePicture() {
return $this->row["profilepicture"]
}
}
Usage:
$user = new User(123);
$username = $user->getUsername();
$profilePicture = $user->getProfilePicture();
That looks like it would work assuming that your config file is correct. Because it is a prepared statement it looks fine as far as security.
They are only passing in the id. One thing you could do to add some security is ensure that the $userid that is passed in is the proper type. (I am assuming an int).
For example if you are expecting an integer ID coming in and you get a string that might be phishy (possible SQL injection), but if you can confirm that it is an int (perhaps throw an error if it isn't) then you can be sure you are getting what you want.
You can use:
is_int($userid);
To ensure it is an int
More details for is_int() at http://php.net/manual/en/function.is-int.php
Hope this helps.
It is safe (at least this part of the code, I have no idea about the database connection part as pointed out by #icecub), but some things you should pay attention to are:
You only need to require your config.php once on the start of the file
You only need to prepare the statement once then call it on the function, preparing it every time might slow down your script:
The query only needs to be parsed (or prepared) once, but can be executed multiple times with the same or different parameters. When the query is prepared, the database will analyze, compile and optimize its plan for executing the query. - PHP Docs
(Not an error but I personally recommend it) Use Object Orientation to help organize your code better and make easier to mantain/understand
As stated by #BHinkson, you could use is_int to validate the ID of the user (if you are using the IDs as numbers)
Regarding HTML escaping, I'd recommend that you already register your username and etc. HTML escaped.

mysql_query not working

Here's PHP code that I'm using:
$query="select * from `myTable` where `email`='$email' limit 0,1";
if(empty($conn))
{
echo "not connected".PHP_EOL;
}
$result = mysql_query($query,$conn);
$row = mysql_fetch_array($result);
if(empty($row))
{
....
When the query is executed in phpmyadmin, I get a single row selected.
However, when I execute the code in php, the row is always empty.
The same goes for several other queries that I've tried to execute. mysql_query always fails.
What could be wrong?
I do not feel there is enough of the code to see what is going on. But based on just what you are showing us, after you get the $result and assign it to $row you have a if statement
if(empty($row)) {...doing something secret...}
which means if something was returned like the row you are expecting NOTHING would happen because (empty($row)) would be false and not execute.
Try this using PDO:
<?php
$email = "example#example.com";
try {
//Instantiate PDO connection
$conn = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
//Make PDO errors to throw exceptions, which are easier to handle
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Make PDO to not emulate prepares, which adds to security
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = <<<MySQL
SELECT *
FROM `myTable`
WHERE `email`=:email
LIMIT 0,1;
MySQL;
//Prepare the statement
$stmt = $conn->prepare($query);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
//Work with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//Do stuff with $row
}
}
catch (PDOException $e) {
//Catch any PDOExceptions errors that were thrown during the operation
die("An error has occurred in the database: " . $e->getMessage());
}
Using mysql_* functions is highly discouraged. It's a guarantee to produce broken code. Please learn PDO or MySQLi from the links in the comment I gave you, and use those instead.
First, confirm $email's value. Echo it right before defining $query to make sure it's what you think it is.
If you've already done that, then you know that's the problem--instead, it's likely that your link identifier $conn is the problem. Instead of using a link identifier, try leaving the second parameter of your query empty, and instead run mysql_connect() at the beginning of your script. That's the best way to do things 99.5% of the time.
See: http://php.net/manual/en/function.mysql-connect.php

Trying to execute a SELECT statement in MYSQL but it is not working

I believe I have the syntax correct, at least according to my textbook. This is just a piece of the file as the other info is irrelevant to my problem. The table name is user, as well as the column name is user. I don't believe this to be the problem, as other sql statements work. Though it isn't the smartest thing to do I know :) Anyone see an error?
try {
$db=new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user,$db_pass);
} catch (PDOException $e) {
exit("Error connecting to database: " . $e->getMessage());
}
$user=$_SESSION["user"];
$pickselect = "SELECT game1 FROM user WHERE user='$user' ";
$pickedyet = $db->prepare($pickselect);
$pickedyet->execute();
echo $pickselect;
if ($pickedyet == "0")
{
echo '<form method="post" action="makepicks.php">
<h2>Game 1</h2>......'
Since you're seemingly using prepared statements, I'd recommend using them to their fullest extent so that you can avoid traditional problems like SQL injection (this is when someone passes malicious SQL code to your application, it's partially avoided by cleansing user inputs and/or using bound prepared statements).
Beyond that, you've got to actually fetch the results of your query in order to display them (assuming that's your goal). PHP has very strong documentation with good examples. Here are some links: fetchAll; prepare; bindParam.
Here is an example:
try
{
$db = new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user, $db_pass);
}
catch (PDOException $e)
{
exit('Error connecting to database: ' . $e->getMessage());
}
$user = $_SESSION['user'];
$pickedyet = $db->prepare('SELECT game1 FROM user WHERE user = :user');
/* Bind the parameter :user using bindParam - no need for quotes */
$pickedyet->bindParam(':user', $user);
$pickedyet->execute();
/* fetchAll used for example, you may want to just fetch one row (see fetch) */
$results = $pickedyet->fetchAll(PDO::FETCH_ASSOC);
/* Dump the $results variable, which should be a multi-dimensional array */
var_dump($results);
EDIT - I'm also assuming that there is a table called 'user' with a column called 'user' and another column called 'game1' (i.e. that your SQL statement is correct aside from the usage of bound parameters).
<?php
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
try
{
// nothing was wrong here - using braces is better since it remove any confusion as to what the variable name is
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e ) // catch all exceptions here just in case
{
exit( "Error connecting to database: " . $e->getMessage() );
}
// this line is unecessary unless you're using it later.
//$user = $_SESSION["user"];
// no need for a new variable here, just send it directly to the prepare method
// $pickselect = '...';
// also, I changed it to a * to get the entire record.
$statement = $db->prepare( "SELECT * FROM user WHERE user=:user" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user', $_SESSION['user'], PDO::PARAM_STR );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
echo $userRow->game1;
Change this user=$user with this user='$user'. Please, note the single quotes.
Moreover, you are executing the query $pickedyet->execute(); but then you do echo $pickselect; which is nothing different from the string that contains the query.
Little hints:
You've to retrieve the result of the query execution.
You're using prepared statement which are very good but you're not really using they because you're not doing any binding.

PDO not returning results from SELECT on more than 1 column

The server is running PHP 5.2.8. PDO has mysql 5.1.30 drivers installed.
Alright, so I am trying to figure out some PDO ( and this is just killing me. When I run the code below, I get the expected results, no problem.
However, whenever I try to add more than one column (or *) to the SELECT, there is no reply from the query - no results whatsoever. I have tried everything - I know it must be something simple. Any suggestions as to why more than one column fails to return any rows?
$hostname = "localhost";
$dbname = "dbname";
$username = "username";
$password = "password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT LastName FROM staff";
foreach ($dbh->query($sql) as $row) {
echo $row['LastName'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
Again, if I try to add columns in the statement stored in $sql to anything other than a single column, I get bupkis. For example:
SELECT FirstName, LastName FROM staff
returns zero results. Both columns exist - if requested separately, they return expected results. When combined, the query takes quite some time, then returns nothing.
No exception is caught by the catch block.
I think you have a number of issues here, mostly in your code that handles reading the values returned by the query. I have taken the liberty of changing a few things and rewriting this to use prepare statements, which is a function that PDO provides that you should take advantage of.
On prepare statements:
Why use them: http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
PHP PDO doc: http://php.net/manual/en/pdo.prepare.php
Here is the core code:
try {
//open database
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//define sql query
$sql = "SELECT LastName FROM staff";
//prepare the query for execution
$qresult = $dbh->prepare($sql);
//insert code below to handle parameters to the sql query here
//execute the query
$qresult->execute();
//fetch the results
foreach ($qresult->fetch(PDO::FETCH_ASSOC) as $row)
{
echo $row['LastName'] . '<br />';
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$qresult = null; //close the result set
$dbh = null; //close the database
Note, that I have replaced the call to query() with a couple of lines that call prepare() then execute(). You can then easily insert the following lines in between the prepare() and execute() calls to handle passing parameterized queries. This will help reduce chances of sql injection.
I have also changed the way you are accessing the retirned valued by specifying that I want them returned as and associative array, PDO::FETCH_ASSOC. This will get you a result set that you can iterate through like you would have using the old mysql interfaces.
If your query was a parameterized query like:
$sql="SELECT LastName FROM staff WHERE LastName=':lastname'";
where :lastname is the parameter.
Here is the code you would insert at the comment to handle this, (this code will handle multiple parameters. Simply add additional elements to the $param array):
//bind parameters to the prepared statement
$param = array(':lastname'=>'Jones');
foreach ($param as $key => $value) {
$qresult->bindValue($key,$value);
}
Make sure you separate the columns in the SELECT with a comma (space on either side of the comma is okay, but not required). If you want to select all columns, have only a * with no other characters.

Categories