I have the following code and whenever the function is called it is inserting the data twice.
The php that is calling the class/function:
$add_amenity = new listing;
echo $add_amenity->add_amenity($_POST['name']);
Here is the function:
public function add_amenity($a)
{
try {
$dbh = new PDO("mysql:host=" . db_host . ";dbname=" . db_name . "",db_user,db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $dbh->prepare("INSERT INTO amenitylist (id,name,icon,isactive) VALUES ('',:a,'','1')");
$q->bindParam(':a', $a);
$q->execute();
$this->_results = $dbh->lastInsertId();
} catch(PDOException $e) {
$this->_results = "ERROR: " . $e->getMessage();
}
}
Related
I'm getting another error with this code. It's:
Connected successfully
Fatal error: Uncaught Error: Call to a member function query() on null in index5.php:29 Stack trace: #0 index5.php(44): User->getAllUsers() #1 index5.php(55): ViewUser->showAllUsers() #2 {main} thrown in index5.php on line 29
I'm trying to echo out data from my database table called "indeximg" but this code gives me the error above. I'm not sure how to fix this. This is my code:
<?php
class Database {
private $host = 'localhost';
private $db_name = 'photos';
private $username = 'root';
private $password = '';
private $conn;
protected function connect() {
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
$this->conn = null;
}
}
class User extends Database {
protected function getAllUsers() {
$sql = "SELECT * FROM indeximg";
$result = $this->connect()->query($sql);
$numRows = $result->num_rows;
if ($numRows > 0) {
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
}
}
class ViewUser extends User {
public function showAllUsers() {
$datas = $this->getAllUsers();
foreach ($datas as $data) {
echo $data['id']."<br>";
echo $data['username']."<br>";
}
}
}
$users = new ViewUser();
$users->showAllUsers();
?>
query() method called from null because you are returning nothing from the connect() function. Add a line as shown in the comment.
protected function connect() {
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
return $this->conn;//Add this line
} catch(PDOException $e) {
echo 'Connection Error: ' . $e->getMessage();
}
$this->conn = null;
}
There are a couple of issues in your connect() function:
First, you are setting $this->conn as null even when it connects successfully.
Second, you are chaining a function to the result of the connect() function that doesn't return anything:
protected function connect()
{
try {
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
die('Connection Error: ' . $e->getMessage()); // Or do something else to handle the error
}
return $this->conn;
}
When I change the IP of my MySQL connection and run this:
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
The try and catch does not work. Its does not catch that error, PDOException or general exception.
The problem is that I did not get any error or a response from PDO. It is pending for a long time.
How can I get the response immediately if there are no connections?
Full code:
case 'mysql':
if ($this->socket) {
$dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
} else {
$dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
}
$commands[] = 'SET SQL_MODE=ANSI_QUOTES';
if (in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) && $this->charset) {
$commands[] = "SET NAMES '" . $this->charset . "'";
}
//**here is the problem //
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
foreach ($commands as $value) {
$this->pdo->exec($value);
}
} catch (PDOException $e) {
echo "Connection to database lost";
}
catch (Exception $e) {
echo "Connection to database lost";
return;
}
even if I try from php manual
$dsn = 'mysql:host=127.0.0.2;port=3306;dbname=dbname';
$username = 'user';
$password = 'pass';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
I am trying to add data into 2 tables using PHP
My PHP code: insert.php
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
echo 'Success!';
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>
Notice is "Success!" but it inserted nothing into database, please guide me the ERROR.Thank you.
You are only preparing the statement - you never execute it. After the prepare call you receive a ready to execute statement, if you execute it with some parameters, it will be inserted in the database:
http://php.net/manual/en/pdostatement.execute.php
You are forget to execute your pdo statements
<?php
session_start();
$db['host'] = "dbhost";
$db['user'] = "user";
$db['pass'] = "pass";
$db['name'] = "dbname";
//making an array with the data recieved
$data = array('f_name' => $_POST['txt_f_name'],
'l_name' => $_POST['txt_l_name'],
'VNum' => $_POST['txtVisaNo']);
try {
// preparing database handle $dbh
$dbh = new PDO("mysql:host=".$db['host']."; dbname=".$db['name']."", $db['user'], $db['pass']);
// set the PDO error mode to exception
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertall = "BEGIN; "
. "INSERT INTO students (f_name, l_name) "
. "VALUES (:f_name, :l_name); "
. "INSERT INTO visa (students_id, VNum) "
. "VALUES (:LAST_INSERT_ID(), :VNum); "
. "$addStdInf->execute($data); "
. "COMMIT;";
$addStdInf = $dbh->prepare($insertall);
$result = $addStdInf->execute();
if ($result) {
echo 'Success!';
} else {
echo 'please check';
}
}
catch(PDOException $e){
echo $sql,'<br />', $e->getMessage();
}
$dbh = null;
?>
I am playing around with PDO, but something weird is happening that I cannot seem to figure out. There are no errors being produced. Just nothing being inserted into the database.
index.php
<?php
error_reporting(E_ALL);
require('includes/classes.php');
require_once('includes/config.php');
$db = new DatabaseCon();
$db->dbConnect($config);
$stmt = $db->prepare("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
?>
classes.php
<?php
error_reporting(E_ALL);
require('config.php');
// Connect to database
// Does not handle anything else
class DatabaseCon {
public $dbh;
// Method to connect to database
function dbConnect($config) {
try {
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
} catch (PDOException $e) {
echo $e->getMessage();
}
}
}
config.php
<?php
error_reporting(E_ALL);
$config = array(
'host' => 'localhost', // Database hostname (usually localhost)
'dbuser' => 'admin_mp', // Database username
'dbpass' => 'mypassword here', // Database password
'dbname' => 'mpdb' // Database name
);
When I navigate to index.php, "hello world" should be inserted into the database, but it's not. Can anyone find what I am doing wrong here?
Change
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
to
$this->dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
Change
$stmt = $db->execute("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
to
error_reporting(E_ALL);
$stmt = $db->dbh->prepare("INSERT INTO images (filename) VALUES (?)");
if (!$stmt) die ('prepare() failed!');
$h = "hello world!";
$rv = $stmt->bindParam(1, $h);
if (!$rv) die ('bindParam() failed!');
$rv = $stmt->execute();
if (!$rv) die ('execute() failed!');
Try this:
index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require('includes/classes.php');
require_once('includes/config.php');
$db = new DatabaseCon();
$db = $db->dbConnect($config);
$stmt = $db->prepare("INSERT INTO images (filename) VALUES (?)");
$stmt->bindParam(1, "hello world!");
$stmt->execute();
?>
classes.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require('config.php');
// Connect to database
// Does not handle anything else
class DatabaseCon {
// Method to connect to database
function dbConnect($config) {
try {
$dbh = new PDO("mysql:host=" . $config['host'] . ";dbname=" . $config['dbname'], $config['dbuser'], $config['dbpass']);
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
return $dbh;
} catch (PDOException $e) {
echo $e->getMessage();
return false;
}
}
}
The DatabaseCon should be acting as a factory to create your connection object.
Thanks to the help of #BenRowe, I found the issue and it is now fixed. A combination of using the $this keyword, and removing the "hello world!" portion from the call to bindParam() fixed it. Seems that the bindParam() method only takes a value based on reference. So I set a random variable $h to "hello world!," and changed bindParam(1, "hello world") to bindParam(1, $h).
Thanks everyone :)
When I try to run this code it will not insert the data into the database?
<?php
class Database {
private $dsn;
function __construct($dbname, $host, $user, $password, $enckey) {
$this->dsn = "mysql:dbname=" . $dbname . ';host=' . $host;
$this->user = $user;
$this->password = $password;
}
private function createDSN() {
return $this->dsn;
}
public function createConnection() {
try {
$dbh = new PDO(self::createDSN(), $this->user, $this->password);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
return $dbh;
}
}
$db = new Database('mytest', 'localhost', 'root', 'hashedpassword', null);
$dbh = $db->createConnection();
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
?>
I don't get an error message
but you have to get it. Asking other people about your database makes very little sense.
Asking the database itself is a way better idea.
add this line to your createConnection() (I dunno what this function for but as you have it)
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
and run your code this way
try {
$sql = $dbh->prepare("INSERT INTO contacts (firstname, lastname) VALUES (?,?)");
$sql->execute(array("abc", "xyz"));
} catch (PDOException $e) {
echo $e->getMessage();
}