OOP selecting data mysql - php

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>';}

Related

PHP MySQL PDO SQLSTATE[HY000]: General error

Please help fix "SQLSTATE[HY000]: General error:" in the following PHP script. Also, refer to the MySQL script in case.
<?php
# MySQL
$host = 'localhost';
$username = 'root';
$password = '';
$dbname = 'procdb';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
do {
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rows) {
foreach($rows as $row) {
print($row[0] . "\n");
}
}
} while ($stmt->nextRowset());
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}
?>
Here's the MySQL Script:
DROP DATABASE IF EXISTS procdb;
DELIMITER $$
CREATE DATABASE procdb;$$
DELIMITER ;
USE procdb;
DROP PROCEDURE IF EXISTS prepend;
DELIMITER $$
CREATE PROCEDURE prepend
(
IN inParam VARCHAR(255),
INOUT inOutParam INT
)
BEGIN
DECLARE z INT;
SET z = inOutParam + 1;
SET inOutParam = z;
SELECT inParam;
SELECT CONCAT('zyxw', inParam);
END;$$
DELIMITER ;
USE procdb;
CALL prepend('abcdefg', #inOutParam);
/*
# Output
// (FieldName1 and its value)
inParam
'abcdefg'
// (FieldName2 and its value)
CONCAT('zyxw', inParam)
'zyxwabcdefg'
*/
What is the cause of the error? Note that adding "$stmt->close();" or "$stmt->closeCursor();" did not help.
Please help.
Thanks
Try this, line
$rows = $stmt->fetchAll(PDO::FETCH_NUM);
Outside While loop
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL Server successfully." . "\n";
$sql = "CALL prepend('abcdefg', #inOutParam);";
$stmt = $pdo->query($sql);
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
$stmt->nextRowset();
$rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
foreach ($rows as $row) {
foreach ($row as $col) {
print $col . "\n";
}
}
} catch (PDOException $e) {
#die("Could not connect to the database $dbname :" . $e->getMessage());
$error = $e->getMessage();
echo $error . "\n";
} catch (Exception $e) {
$error = $e->getMessage();
echo $error . "\n";
} finally {
$pdo = null;
echo "Connection closed." . "\n";
}

SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected error

my code and I take a error. I wonder how I solve problems
<?php
include_once 'simple_html_dom.php';
try {
$dsn = "mysql:host=localhost;db=test";
$username ="root";
$password = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=> 'SET NAMES UTF8' ,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION );
$conn = new PDO($dsn, $username, $password, $options);
} catch (Exception $ex) {
echo "Hata kodu " . $ex->getMessage();
}
// markaları alalım
$markaurl ="https://www.xxxx/chip-tuning";
$markaurlhtml = file_get_html($markaurl);
foreach ($markaurlhtml->find('div[class="darkGrid mediumBordered"] ul[id="brandsList"] a') as $markalar0) {
/* //Buna hiç gerek yokmuş üstteki kod gayet güzel ve esnek oldu :D
foreach ($markalar0->find('ul[id="brandsList"] a') as $markalar0) {
echo $markalar->href . "<br>";
} */
// echo $markalar0->href . "<br>";
// $mrk = $markalar0->href;
try {
$deyim = $conn->prepare("INSERT INTO remap_marka (marka) VALUES (?)");
$deyim->bindParam(1, $mrk);
$deyim->execute();
} catch (Exception $ex) {
echo $ex->getMessage() . "<br>";
}
}
?>
This is a solution you need for your code. Please replace it:
<?php
include_once ("simple_html_dom.php");
try {
$dsn = "mysql:host=localhost;dbname=test";
$username = "root";
$password = "";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$conn = new PDO($dsn, $username, $password, $options);
} catch (PDOException $ex) {
echo "Hata kodu " . $ex->getMessage();
}
// markaları alalım
$markaurl ="https://www.xxxx/chip-tuning";
$markaurlhtml = file_get_html($markaurl);
foreach ($markaurlhtml->find('div[class="darkGrid mediumBordered"] ul[id="brandsList"] a') as $markalar0) {
/*
// Buna hiç gerek yokmuş üstteki kod gayet güzel ve esnek oldu :D
foreach ($markalar0->find('ul[id="brandsList"] a') as $markalar0) {
echo $markalar->href . "<br>";
}
// echo $markalar0->href . "<br>";
// $mrk = $markalar0->href;
*/
try {
$deyim = $conn->prepare("INSERT INTO remap_marka (marka) VALUES (?)");
$deyim->bindParam(1, $mrk);
$deyim->execute();
} catch (Exception $ex) {
echo $ex->getMessage() . "<br>";
}
}
?>
I hope it is useful, regards :)

PHP :: Stumped on how to reference specific row in a mysql select array...?

I am just not making a connection here, and im not getting search results that are helping me enlighten myself.
I am pulling data from mysql into an array. But I am tottaly missing how I reference a specific row later.
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
foreach($chamberstate as $row) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
$array = array($chamber,$schedule,$runningnow,$temp);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Ok, so all the data is in the array. But how do I , say, print the $schedule where $chamber == 1 ?
I feel so dumb for not getting this.....
You were close with your original code but the $array variable was being overwritten each time through the loop. If you need to access the values throughout your page ou should be able to do so with an approach like this.
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
/* Populate this array for later use */
$chambers=array();
foreach( $chamberstate as $row ) {
$chamber = $row['Chamber'];
$schedule = $row['Schedule'];
$runningnow = $row['RunningNow'];
$temp = $row['ChangingTemp'];
/* This will overwrite any values in the $array variable with each iteration through the loop */
/*
$array = array( $chamber, $schedule, $runningnow, $temp );
*/
$chambers[]=array( 'chamber'=>$chamber, 'schedule'=>$schedule, 'running'=>$runningnow, 'temp'=>$temp );
}
/* later, when you need to access the various values, you can reference via the index */
echo $chambers[ 1 ]['chamber'];
/* or */
echo $chambers[ 23 ]['schedule'];
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=FermentorDB', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$chamberstate = $conn->query('SELECT * FROM ChamberState' . $conn->quote($mac));
$caray = array();
foreach($chamberstate as $row) {
$caray[$row['Chamber']]['Chamber'] = $row['Chamber'];
$caray[$row['Chamber']]['Schedule'] = $row['Schedule'];
$caray[$row['Chamber']]['RunningNow'] = $row['RunningNow'];
$caray[$row['Chamber']]['ChangingTemp'] = $row['ChangingTemp'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
print_r($carray['1']);
?>

PDO Read From Database

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;
}
}
?>

Data does not display from PDO and MySQL

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>";
?>

Categories