I keep getting:
Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2031 ' in XXXXX
The code I'm using is:
$CR = $this->db->query('SELECT COUNT(*) FROM entities WHERE (entities.typeId = 2 OR entities.typeId = 1)');
$count = $CR->fetchColumn();
I have tried using prepare instead but I get the same result.
Any idea what's causing this and how I can fix it?
class Database extends PDO {
function __construct($user = 'xxx', $pass = 'xxx', $database = 'abc', $host = 'xxx', $port = 'xxx')
{
parent::__construct('mysql:host=' . $host . ';port=' . $port . ';dbname=' . $database, $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_PERSISTENT, FALSE);
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$this->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
$this->exec("SET NAMES utf8");
}
}
$this->db = new Database();
try to remove:
$this->setAttribute(PDO::ATTR_PERSISTENT, FALSE);
Related
Update function
I am getting an error while updating data from database.
sub update
{
my $sql = "UPDATE Data SET NAME = ?, ADDRESS=?, PHONE_NO=?,
DATE_OF_JOINING=?, ROLE_ASSIGN=?, SALARY=? WHERE ID = ?";
my $sth = $dbh->prepare($sql);
print("Enter ID to update : ");
chomp(my $ID = <STDIN>);
print("NAME : ");
chomp(my $NAME = <STDIN>);
print("ADDRESS : ");
chomp(my $ADDRESS = <STDIN>);
print("PHONE_NO : ");
chomp(my $PHONE_NO = <STDIN>);
print("DATE_OF_JOINING : ");
chomp(my $DATE_OF_JOINING = <STDIN>);
print("ROLE_ASSIGN : ");
chomp(my $ROLE_ASSIGN = <STDIN>);
print("SALARY : ");
chomp(my $SALARY = <STDIN>);
$sth->bind_param(1,$NAME);
$sth->bind_param(2,$ADDRESS);
$sth->bind_param(3,$PHONE_NO);
$sth->bind_param(4,$DATE_OF_JOINING);
$sth->bind_param(5,$ROLE_ASSIGN);
$sth->bind_param(6,$SALARY);
$sth->bind_param(7,$ID);
$sth->execute();
print("The record has been updated successfully!");
$sth->finish();
$dbh->disconnect();
}
After executing above function when i try to view updated data :
sub query_links
{
my ($dbh) = #_;
my $sql = "SELECT * FROM Data";
my $sth = $dbh->prepare($sql) or die $DBI::errstr;
$sth->execute() or die $DBI::errstr;
$sth->dump_results();
$sth->finish();
}
Error:
DBD::mysql::st execute failed: MySQL server has gone away at mini.plx line 94,
<STDIN> line 9.MySQL server has gone away
The error message means that the connection to your database has been lost.
You don't show us any code that creates your connection, so it's hard to know what might have gone wrong there. You might consider adding the mysql_auto_reconnect flag when connecting to the database.
my $dbh = DBI->connect($dsn, $user, $password, {
mysql_auto_reconnect => 1,
});
You can also change this setting after the database connection has been set up.
$dbh->{mysql_auto_reconnect} = 1;
Update: As ikegami points out in a comment, you disconnect from the database at the end of update() - and you don't show any code demonstrating that you reconnect before using the connection again in query_links(). That will cause this problem.
I'm trying to test my prepared statement that is protecting one field to get the error message in case of SQL injection. I tried until now thousands of attacks, and all of the values I gave were accepted. Am I using a wrong syntax or attack? I can't see where the problem is. Here is my code:
try {
// $host = "localhost";
// $username = "root";
// $password = "root";
// $db_name = "pokemon";
$conn = new PDO('mysql:host='.$host.';dbname='.$db_name.';', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$meldung="";
$name =$_REQUEST['name'];
$gewicht = $_REQUEST['Gewicht'];
$größe =$_REQUEST['Größe'];
$spezies = $_REQUEST['Spezies'];
$stufe =$_REQUEST['Stufe'];
$atacke =$_REQUEST['Attacke'];
$array = explode(',', $_REQUEST['Attacke']);
$stmt = $conn->prepare("INSERT INTO Pokemon (`Name`,`Gewicht`,`grosse`,`spezies`,`stufe`) VALUES (:Name, '".$gewicht."', '".$größe."', '".$spezies."', '".$stufe."')");
$stmt->bindParam(':Name', $name);
// $stmt->bindParam(':Gewicht', $gewicht);
// $stmt->bindParam(':grosse', $größe);
// $stmt->bindParam(':spezies', $spezies);
// $stmt->bindParam(':stufe', $stufe);
$stmt->execute();
}
catch(PDOException $e)
{
$meldung = "Error: " . $e->getMessage();
echo $meldung;
}
thanks
I attached index.php file. I get error on line 37 as:
"Database connection error: Please check the database name you provided".
I checked database name its correct and tried 2 different database names but I get same error. Can someone tell me whats wrong in this code?
This is my index.php file.
if (( isset( $_POST ) && $_POST['submit'] == 'submit' )) {
$SS_license = trim( $_POST['license'] );
$db_host = trim( $_POST['host'] );
$db_name = trim( $_POST['database_name'] );
$db_pass = trim( $_POST['database_password'] );
$db_user = trim( $_POST['database_user'] );
$flag = 0;
if (( 'Database connection error: Please check the host name, user name and password you provided' || $con = mysql_connect( $db_host, $db_user, $db_pass ) )) {
if (mysql_select_db( $db_name, $con )) {
$message .= 'Successfully connected to database<br>';
$flag = 1;
}
else {
$message .= 'Database connection error: Please check the database name you provided<br>';
}
}
else {
$message .= 'Database connection error: Please check the host name, user name and password you provided<br>';
}
if ($flag == 1) {
$fp = fopen( BaseUrl . DS . 'includes' . DS . 'db_inc.php', 'w' );
$string = '<?php';
please tell me where to edit this code so I can connect to databse.
you should try using below code, this works fine for me.
<?php $servername = "localhost";$username = "your_username";$password = "your_password";$dbname = "your_DBname"; $conn = mysqli_connect($servername, $username, $password, $dbname);if (!$conn) {die("Connection failed: " . mysqli_connect_error()); } ?>
I am trying to connect to MySQL server (hosted by godaddy) from php using PDO.
But I get this error :
An error occured : SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
Note that this is not a database I host.
I was simply given the username and password to construct the database, create the users etc.
function ConnectToDb()
{
try{
$dns = 'mysql:host=1.1.1.1;dbname=dummyDbName';
$username = 'dummyUser';
$password = 'dummyPassword';
$LINK = new PDO($dns, $username, $password);
$LINK->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$LINK->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!$LINK){
die('Could not connect : ' .mysql_error());
}
else{
return $LINK;
}
} catch (PDOException $ex){
echo "An error occured : " .$ex->getMessage();
}
}
I know that this works on localhost.
I'm using it no problem, but as soon as I try to connect to the live database it fails.
Anyone has an hint?
Thanks
Follow this format:
$user = "username";
$pass = "password";
$host = "localhost";
$db = "yourDbname";
$dns = "mysql:host=" . $host . ";dbname=" . $db;
$dbh = new PDO($dns, $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
when you have to do a query (just an example):
$theid = 10;
$statement = $dbh->prepare('SELECT * FROM yourtable WHERE id = ? and name = ?');
$statement->execute(array($theid,'baronth'));
if you want to see if there's some errors while connecting or doing queryes (and you know how try-catch works), surround it with:
try {
all the code that you wan't to check
}
catch (PDOException $e) {
echo $e->getMessage();
}
it will echo the error.
I just changed all my code from the old mysql driver to PDO.
So far I find that a lot of basic functionalities doesn't exist! Ex. no equivalency to mysql_num_row .. and so on (but that's not the point of this post :/ )
Usually with mysql driver, I'd do:
$result = mysql_query($query);
if(!$result){
displayError(mysql_error());
}
How do you do similar thing using PDO?
Have a look at the documentation here there are 3 modes :
PDO::ERRMODE_SILENT (default)
PDO::ERRMODE_WARNING
PDO::ERRMODE_EXCEPTION
I suggest you enable the last, which causes an exception to be thrown on error :
$pdo = new PDO($dsn,$user,$pass,$options); // Example connection
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
then surround your statement in a try/catch block
try {
// your query here
} catch (PDOException $e) {
echo 'Query failed: ' . $e->getMessage();
}
Separate note - mysql_num_row in PDO :
$sql = "SELECT count(*) FROM `table` WHERE x = y";
$result = $con->prepare($sql);
$result->execute();
$number_of_rows = $result->fetchColumn()
Use try { } catch {}
<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Reference