Sorry if the title is vague, was unsure how to word it.
Currently, I'm trying to just do a simple piece of php that runs a query and displays all the data in the database, but no data is displaying the page is just completely blank.
Here is the code:
<?php
$username = "user";
$password = "pass";
try {
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
I've never worked with PDO before so I've been following a guide/reading different SO questions trying to get a grasp on it. One line that I think may be screwing up is this line:
$stmt->execute(array('id' => $id));
I don't understand what that line is doing and if an I can get an explanation that would be great. I believe I understand the logic behind the rest of the code though.
This should solve your problem (it worked on my server).
Plus, I added the <table> and </table> tags and placed in their respective locations.
<?php
$username = "user";
$password = "pass";
try {
// uncomment for testing purposes as noted by jeroen
// $conn = new PDO('mysql:host=localhost;dbname=database', $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
$stmt = $conn->prepare('SELECT * FROM contacts');
$stmt->execute(array('id' => $id));
// $stmt->execute(); // as noted by Mike Brant
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<table>";
if ( count($result) ) {
foreach ($result as $query_row)
{
extract($query_row);
echo '<tr>';
echo '<td>'.$fname.'</td>';
echo '<td>'.$lname.'</td>';
echo '<td>'.$title.'</td>';
echo '<td>'.$deparment.'</td>';
echo '<td>'.$email.'</td>';
echo '<td>'.$cell.'</td>';
echo '<td>'.$handle.'</td>';
echo '<td>'.$steam.'</td>';
echo '<td>'.$skype.'</td>';
echo '</tr>';
}
}
echo "</table>";
?>
Related
We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don't want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?
Connection to Database:
<?php
$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';
try {
$db = new PDO($constr, $dbUser, $dbPW);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$rez = "Connected";
//echo $rez;
} catch(PDOException $ex) {
$rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
//echo $rez;
}
?>
Code to display the results on the page:
<?php
include 'db.connect.php';
$sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";
$stmt = $db->prepare($sql);
$stmt->execute();
$num_rows = $stmt->rowCount();
//echo $num_rows;
if($num_rows > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['ts_id'];
$name = $row['name'];
echo "<tr>";
echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
echo "</tr>";
}
include 'db.close.php';
?>
Thank you in advance!
You might try changing your query to:
$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";
I don't know if that will filter out your error message
I have made a code using PDO to read a table from a database.
I try to echo my result but I get a blank page without error.
My Code Is:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
But the echo is empty without any error.
What I am doing wrong?
Thank you All!
Few things to change:
dont forget $
if your going to catch the error, catch the whole pdo code
You can use rowCount() to count the rows
echo something if the record count is 0
include 'config.php';
$id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->rowCount() != 0)
{
$row = $result->fetch(PDO::FETCH_BOTH);
echo $row['Data1'];
echo $row['Data2'];
}else{
echo 'no row found';
}
}catch(PDOException $e){
echo "error " . $e->getMessage();
}
Also use prepared statements for example:
$result = $conn->prepare("SELECT * FROM mytable WHERE id=:id");
$result->execute(array(':id'=>$id));
I'm assuming there's only one record with the id "264540733647332".
The issue is that $result->fetchColumn() call reads first row in the result set and then advances to the next result. Since there's only one of the results, the subsequent call to $result->fetchAll() returns nothing, hence no data displayed.
To fix this replace fetchColumn with rowCount:
<?php
include 'config.php';
id = "264540733647332";
try {
$conn = new PDO("mysql:host=$hostname;dbname=mydata", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$result = $conn->query("SELECT * FROM mytable WHERE id='".$id."';");
if ($result->fetchColumn() != 0)
{
foreach ( $result->fetchAll(PDO::FETCH_BOTH) as $row ) {
$Data1 = $row['Data1'];
$Data2 = $row['Data2'];
echo $Data2;
}
}
?>
I'm new to OOP and just trying to migrate from mysql_, but I'm running into some issues while migrating.
$konek = new PDO('mysql:host=localhost;dbname=mydatabase', root, root);$hasil = $konek->query("SELECT * FROM `tabel`");
while ($data = $hasil->fetch_object()) {
echo '<td>'.$data->something.'</td>';}
It doesn't work or show an error, but when I replace the first line with mysqli it works:
konek = new mysqli('localhost','root','root','mydatabase');
Any help would be really appreciated.
I assume in your code, it is coded as string: (or is root defined?)
$konek = new PDO('mysql:host=localhost;dbname=mydatabase', root, root);
Clearly, in your example, if it's a type change it to:
$konek = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', 'root', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
Refactor your code into this:
error_reporting(E_ALL);
ini_set("display_errors", 1);
try {
$konek = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', 'root', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$hasil = $konek->query("SELECT * FROM `tabel`");
echo '<table>';
while ($row = $hasil->fetch(PDO::FETCH_OBJ)) {
echo '<tr>';
echo '<td>' . $row->column_name . '</td>';
echo '</tr>';
}
echo '</table>';
1)User name and password should be quoted string
2) use try catch
3) use prepare and execute the query
4) then fetch
try like this:
try {
$konek = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', 'root');
$konek->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
die( 'ERROR: ' . $e->getMessage());
}
try {
$hasil = $konek->prepare("SELECT * FROM `tabel`");
$hasil->execute();
while ($data = $hasil->fetch(PDO::FETCH_OBJ)) {
echo '<td>'.$data->something.'</td>';
}
}
catch(PDOException $e) {
die( 'ERROR: ' . $e->getMessage());
}
Please provide an error message it echoes.
MY best guess:
http://www.php.net/manual/en/pdostatement.fetchall.php
Try replacing
while ($data = $hasil->fetch_object()) {
echo '<td>'.$data->something.'</td>';}
with
while ($data = $hasil->fetchAll()) {
echo '<td>'.$data->something.'</td>';}
I am trying to set a certain cell in a database to a variable in PDO. The code I am using now is:
$dbuser = "root";
$dbpass = "root";
$player = "ryr11";
//$player = $_GET["pname"];
try {
$conn = new PDO("mysql:host=localhost;dbname=users", $dbuser, $dbpass);
$stmt = $conn->prepare("SELECT * FROM players WHERE username = :player");
$stmt->execute(array("player" => $player));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
print_r($row);
}
} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo "ERROR: " . $e->getMessage();
}
I want each column to have it's own variable, so I can echo the cell content. As of now, it is only showing it in an array.
echo $row['cell_name'];
fetchAll() returns an associative array.
while ($result = $stmt->fetch())
{
echo 'username : '. $result["username"].'<br />';
echo 'cell_name2 : '. $result["cell_name2"].'<br />';
echo 'cell_name3 : '. $result["cell_name3"].'<br />';
.....
...
etc
}
or you can use a html table style
The following script:
<?php
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
is returning:
Warning: Invalid argument supplied for foreach() in myscript.php on line 5
If I execute: Select * from phrases; in a SQL browser, I get back a long list of results, with regard to the columns phrase and score. What am I doing wrong?
There are 2 examples in this answer.
The first example I found at http://juanmanuelllona.blogspot.ca/
Am providing what I hope will be a solution.
1)
try {
$db = new PDO("sqlite:./path/phrases");
echo 'database open';
$sql = "SELECT * FROM phrases";
$obj= $db->query($sql) ;
foreach ($obj as $row)
{
print('Phrase ='.$row['phrase'].' Course='.$row['score']. '<br/>'); // or <br/>
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
2)
And this suggestion taken from an example at http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=phrases", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM phrases";
foreach ($dbh->query($sql) as $row)
{
print $row['phrase'] .' - '. $row['score'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
You need to use echo statement:
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
echo $row['phrase'];
echo $row['score'];
}
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases;'); // remove the Semicolon
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
try removing the Semicolon inside the statement.