Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.
Related
I'm learning to connect to my database and create/read/update/delete information from different tables. Currently I'm using PDO instead of mysqli because I'm having an easier time with prepared statements. What I'm trying to do right now doesn't actually have any value, I just want to know WHY this is happening. Here's my code:
//pdo connection
try {
$conn = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_user, $db_pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//READ FROM DB
$stmt = $conn->prepare('SELECT * FROM objects where ID = :id');
$stmt->execute(array(':id'=>8));
print_r($stmt->fetch(PDO::FETCH_OBJ));
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$results[] = $row;
}
print_r($results);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
Now, what's happening is that if I print_r in this order then only the first print_r works and vice versa (assuming I also move the while loop with the print_r($results) statement. Why is it that I am only allowed to do this once and whichever is first negates the second?
EDIT: Clarification.
I have writen this pice of code that should insert into my Database some event data, but it does not insert a thing in the DB, can you tell me why?
try {
$pdo = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $excepiton ) {
echo "Connection error :" . $excepiton->getMessage();
}
try{
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name) VALUES (:event_id, :event_end_time, :event_location, :event_name) ON DUPLICATE KEY UPDATE event_id = :event_id, event_end_time = :event_end_time, event_location = :event_location, event_name = :event_name";
$stm = $db->prepare($sql);
$stm->execute(array(":event_id" => $event[id], ":event_end_time" => $event[end_time], ":event_location" => $event[location], ":event_name" => $event[name]));
}
catch ( PDOException $exception )
{
// decomentati sa vedeti erorile
echo "PDO error :" . $exception->getMessage();
}
Thanks
The code you've posted is different than the code you're running as the posted code would result in a syntax error at parse time and never actually run.
However, what's happening is the SQL being sent to the prepare method is not valid in some way so that the result returned and stored in $stm is a boolean (false) rather than a valid statement object. Double check your SQL (you could try running it in another application such as phpMyAdmin or via the mysql command-line program) to ensure its validity. You could also add some error handling to find the cause with:
$stm = $db->prepare($sql);
if (!$stm) {
die($db->errorInfo());
}
Edit: You've modified the posted source code which now shows use of exception handling. However, you've commented out the line that echos the exception message. This information will be useful in telling you what's causing the error condition. Uncomment to see the message (which will most likely inform you that the SQL is invalid and which part of it caused the error).
Try to remove the <br> tag from the first line and a " is messing
$sql = "INSERT INTO events_DB (event_id, event_end_time, event_location, event_name);"
Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);
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
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.