I am trying to list data from two specific columns in a table. Whenever I go to the file, it returns a server error. When I remove the while loop, it executes perfectly, so I have no idea what I am doing wrong.
Here's the error:
Server error The website encountered an error while retrieving
http://dayzlistings.com/reg-whitelist.php. It may be down for
maintenance or configured incorrectly. Here are some suggestions:
Reload this webpage later. HTTP Error 500 (Internal Server Error): An
unexpected condition was encountered while the server was attempting
to fulfill the request.
try {
$dbh = new PDO('mysql:host=localhost;dbname=dbname','dbuser','dbpass');
$sql = "SELECT * from wp_cimy_uef_data";
$q = $dbh->prepar($sql);
$q->execute();
while($row = $q->fetchall() {
echo $row['USER_ID'];
echo $row['VALUE'];
}
}
$dbh = null;
} catch (PDOException $e) {
print "Error from Dedicated Database!: " . $e->getMessage() . "<br/>";
die();
}
500 means something wrong when you interact with the server, e.g. access db.
And $row['USER_ID'] will never work, instead you should use $row[0]['USER_ID'].
isn't fetchAll() returns the whole table as an array?..
you don't need to while loop $row.. just do $row = $q->fetchAll() without while and print_r the whole array and see what you get..
and if you still wanna do while I think you may use
while($row = $q->fetch()){
// rest of the code here
}
Also you cannot put annything between try catch..
try{
//code
}
$dbh = null; //**This is not allowed by the way...**
catch(PDOException $e){
//code
}
Dins
Related
My .php includes quote.php followed with the rest of the page.
When the connection fails, I see "Fatal error: Uncaught mysqli_sql_exception: ----- include_once('C:\xampp\htdocs...') ----
and the remainder of the page does not load.
What must I do to display an error message, THEN the rest of my page?
Your situation is a rare case when using a try catch is justified.
All you need to do it wrap the include in a try-catch:
try {
require 'quote.php';
} catch(\Throwable $e) {
error_log($e); // for the future inspection
echo "Problem loading this part of page";
}
That's all. The error message will be shown and the rest of the page will be loaded.
But of course this approach should only be used when the content from quote.php is optional. In the every other case there must be no local try-catch but a site-wide error handler.
php / msqli is throwing exceptions. You need to write exception handler code (try { } catch (mysqli_sql_exception $e) { } code in your program to handle errors.
As a quick and sleazy workaroud for the current state of your code you can put this line of code at the top of your page. give this line of code
mysqli_report(MYSQLI_REPORT_OFF):;
This will suppress php exceptions and warnings, and let you rely completely on mysqli_connect_errno() to catch your errors.
Using #O. Jones idea and some nasty GoTO's, this does the job. The warnings and error are still displayed. The rest of the page is able to load now.
<?php
mysqli_report(MYSQLI_REPORT_OFF);
$dbServer = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "project_01";
$conn = mysqli_connect($dbServer, $dbUsername, $dbPassword, $dbName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to the MySQL Database: ";
goto end;
}
$sql = "SELECT * FROM tbl_quotes";
if ($result=mysqli_query($conn,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
$rand = random_int(1,$rowcount);
} else {
echo "No records were found";
goto end;
}
$sql = "SELECT quote, credit FROM tbl_quotes where ID = $rand";
if ($result = mysqli_query($conn, $sql)) {
// Fetch one and one row
while ($row = mysqli_fetch_row($result)) {
printf ("%s" . " - " . "(%s)\n", $row[0], $row[1]);
}
// Free result set
mysqli_free_result($result);
}
end:
?>
Thanks to all who looked.
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()));
}
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.
I'm new to PDO and I wanna do it right from the beginning - I'm going to replace my old mysql_ functions on a site.
Have I got it right?:
Should I put the connection code in a try/catch and save it to a file, and include it on top of the page. Then put the queries in try/catch as well.
Or:
Should I put the connection code in a file and include it in the in the top of the try/catch statement above the query?
ver1:
include('pdo.php'); // try/catch in file
try {
$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();
}
ver2:
try {
include('pdo.php'); // no try/catch in file
$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();
}
Or should I put the try/catch in both places?
You should do both and even more :
Set an error handler that displays a message to the user and stops the PHP (see set_error_handler)
When you initiate the connexion, add a try/catch and throw an error if you catch an exception. Your website won't run without database connection i guess.
Do a try/catch around your queries to recover gracefully from error (when you can)
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);