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";
}
Related
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 :)
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 am new to pdo as I am just moving into it from the traditional method of doing queries. Below is what I have wrote and it works. My concern now is that if there any error in any of the query either the select,insert or update they are all capture by that one catch but then I cant pin point exactly to the error. So will multiple try and catch be the right direction ?
try {
$dsn = 'mysql:dbname='.dbDatabase.';host='.dbHost;
$link = new PDO($dsn, dbUser, dbPassword );
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$link->beginTransaction();
$rollBackStatus="False";
try
{
$selectQuery1 ="Select ......";
$selectQueryResult1 = $link->prepare($selectQuery1);
$selectQueryResult1->bindParam(':uname', $userName);
$selectQueryResult1->execute();
$n1=$selectQueryResult1->rowCount();
//echo "TEST : ".$n1;
if($n1==1)
{
$row1 = $selectQueryResult1->fetch();
$userID=$row1['userID'];
if($row1['up']==$up){
$insertQuery1 ="Insert .......... ".
$insertQueryResult1 = $link->prepare($insertQuery1);
$insertQueryResult1->bindParam(':uID', $userID);
$insertQueryResult1->bindParam(':uIP', $userIP);
if($insertQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
$updateQuery1 ="Update ........ ";
$updateQueryResult1 = $link->prepare($updateQuery1);
$updateQueryResult1->bindParam(':uID', $userID);
if($updateQueryResult1->execute()){
}
else{
$rollBackStatus="True";
$link->rollback();
}
}
}
catch(PDOException $pe)
{
$rollBackStatus="True";
die("Error in selectQuery1 :" . $pe->getMessage());
$link->rollback();
}
if($rollBackStatus=="False"){
$link->commit();
$link=null;
if($headerSent!="")
{
header($headerSent);
}
}
You can check any error after execute query with following method.
$selectQueryResult1->execute();
$arr = $selectQueryResult1->errorInfo();
print_r($arr);
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>';}
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.