How to insert data in multiple table with one query PDO mysql? - php

I need to insert data in mysql database with one query in PDO mysql.
I need the same thing what is here done with mysqli multi query.
This works fine
$insert ="
insert into comments (user_id,comment) values('$user_id','$comment');
insert into comments2 (user_id,comment) values('$user_id','$comment');
$run = mysqli_multi_query($con,$insert);
But how can I do this in PDO
connection.php :
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'hotwall'; //name of your database
$this->port = '3306';
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
what should I do here to insert in another table
$query = $bdd->execute('insert into comments (user_id,comment)
values('$user_id','$comment')');

Use 2 queries, not one. Of course it must be parameterized queries.
$stmt = $pdo->prepare("insert into comments (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
$stmt = $pdo->prepare("insert into comments2 (user_id,comment) values(?,?)");
$stmt->execute([$user_id,$comment]);
is all the code you need.

Related

How to fetch data from a MS-SQL Server Database using PHP?

I'm trying to fetch data from a SQL Server database. After debugging, I could figure there's something wrong with the function.
Here's the code:
db.php
class Db{
public static function getConnection() {
$server='xxx';
$database='xxx';
$user='xxx';
$password='xxx';
$dsn="dblib:host=" . $server . ";dbname=" . $database;
try {
$conn = new PDO($dsn, $user, $password);
}
catch (PDOException $e) {
echo 'SQL SERVER CONNECTION ERROR: ' . $e->getMessage();
}
return $conn;
}
}
functions.php
class Functions {
function getAcademicYear() {
$db = new Db();
$conn = $db->getConnection();
$conn->beginTransaction();
$sql = "SELECT academicYear FROM AcademicYear ORDER BY academicYearId DESC LIMIT 5";
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$conn->commit();
echo $result;
} else {
$conn->rollback();
echo "false";
}
}
}
The function is returning false. Can you please review it and point out any mistakes?

PHP - Call to a member function query() on null - Error [duplicate]

This question already has answers here:
Fatal error: Call to a member function query() on null
(2 answers)
Closed 5 years ago.
I have the following code in php for connecting to my database:
<?php
class MY_SQL{
private $username;
private $password;
private $conn;
public function __construct($SERVERNAME){
$this->username = "username";
$this->password = "password";
if($SERVERNAME == "data_"){
$server = "Servername";
}
else {
$server = $SERVERNAME;
}
// Create connection
$conn = new mysqli($server, $this->username, $this->password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
public function SQLCommand($cmd) {
if ( $this->conn->query($cmd) === TRUE ) {
echo "New record created successfully";
} else {
echo "Error: " . $cmd . "<br>" . $conn->error;
}
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$database = new MY_SQL("Servername");
$database->SQLCommand($sql);
?>
I get the following error:
Fatal error: Call to a member function query() on null
What is going wrong?
$this->conn = $conn; in __construct()
I would suggest you to improve your class with this example (taken from https://github.com/opencart/opencart/blob/master/upload/system/library/db/mysqli.php)
final class My_SQLi
{
private $connection;
public function __construct($hostname, $username, $password, $database, $port = '3306')
{
$this->connection = new \mysqli($hostname, $username, $password, $database, $port);
if ($this->connection->connect_error) {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno);
}
$this->connection->set_charset("utf8");
$this->connection->query("SET SQL_MODE = ''");
}
public function query($sql)
{
$query = $this->connection->query($sql);
if (!$this->connection->errno) {
if ($query instanceof \mysqli_result) {
$data = array();
while ($row = $query->fetch_assoc()) {
$data[] = $row;
}
$result = new \stdClass();
$result->num_rows = $query->num_rows;
$result->row = isset($data[0]) ? $data[0] : array();
$result->rows = $data;
$query->close();
return $result;
} else {
return true;
}
} else {
throw new \Exception('Error: ' . $this->connection->error . '<br />Error No: ' . $this->connection->errno . '<br />' . $sql);
}
}
public function escape($value)
{
return $this->connection->real_escape_string($value);
}
public function countAffected()
{
return $this->connection->affected_rows;
}
public function getLastId()
{
return $this->connection->insert_id;
}
public function isConnected()
{
return $this->connection->ping();
}
public function __destruct()
{
$this->connection->close();
}
}
$sql = "INSERT INTO _test(test1, test2) VALUES ('hello','hi');";
$mysql = new My_SQLi('host', 'user', 'password', 'db');
$result = $mysql->query($sql);

PHP Fatal error: Call to a member function fetchAll() on a non-object - PDO Statement returns TRUE

Someone please help, I have been struggling with this for hours. I am trying to retrieve all rows but keep getting this error. It is returning bool(true) but wont go any further than that. My code is posted underneath:
Event.load.php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/database.php';
try
{
$db = new Database();
$user = new USER( $db );
$stmt = $user->runQuery( 'SELECT id, name, DATE_FORMAT( start_date, "%D %b %Y" ) start_date, DATE_FORMAT( start_date, "%l:%i %p" ) start_time, DATE_FORMAT( end_date, "%D %b %Y" ) end_date, DATE_FORMAT( end_date, "%l:%i %p" ) end_time, description FROM event');
$rslt= $stmt->execute();
$result = $rslt->fetchAll();
// header("Content-Type: application/json", true);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Database.php
class Database
{
public function dbConnection()
{
$this->conn = null;
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);
}
catch(PDOException $exception)
{
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
include_once 'user.php';
$db = new Database();
$user = new USER($db);
?>
User.php
<?php
require_once 'database.php';
class USER
{
private $conn;
public function __construct()
{
$database = new Database();
$db = $database->dbConnection();
$this->conn = $db;
}
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
public function lasdID()
{
$stmt = $this->conn->lastInsertId();
return $stmt;
}
public function register($uname,$email,$upass,$code)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass,tokenCode)
VALUES(:user_name, :user_mail, :user_pass, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function login($email,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT * FROM users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if($userRow['userStatus']=="Y")
{
if($userRow['userPass']==md5($upass))
{
$_SESSION['userSession'] = $userRow['userID'];
return true;
}
else
{
header("Location: index.php?error");
exit;
}
}
else
{
header("Location: index.php?inactive");
exit;
}
}
else
{
header("Location: index.php?error");
exit;
}
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_start();
session_destroy();
$_SESSION['userSession'] = false;
}
function send_mail($email,$message,$subject)
{
mail($email, $subject, $message);
}
}
As you already have said, the execute method returns true (so a boolean).
Now you try to call the method fetchAll on this boolean which of course does not work.
As Charlotte Dunois has already suggested in the comment section, you should take a look at the php manual. There you can see, that you must call the fetchAll method as a member of the statement.
So the Event.load.php should look something like this:
try
{
$db = new Database();
$user = new USER( $db );
$stmt = $user->runQuery( '...');
$rslt= $stmt->execute();
$result = $stmt->fetchAll(); //<----THIS LINE IS IMPORTANT
// header("Content-Type: application/json", true);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

PHP not showing anything

I cannot see anything when on my xampp server and displays an empty page. I am trying to find the error but failed. anyone can help would be appreciated
here is class.db.php
<?php
class db {
private $conn;
private $host;
private $user;
private $password;
private $baseName;
private $port;
private $Debug;
function __construct($params=array()) {
$this->conn = false;
$this->host = 'localhost'; //hostname
$this->user = 'root'; //username
$this->password = ''; //password
$this->baseName = 'db'; //name of your database
$this->debug = true;
$this->connect();
}
function __destruct() {
$this->disconnect();
}
function connect() {
if (!$this->conn) {
try {
$this->conn = new PDO('mysql:host='.$this->host.';dbname='.$this->baseName.'', $this->user, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
}
if (!$this->conn) {
$this->status_fatal = true;
echo 'Connection BDD failed';
die();
}
else {
$this->status_fatal = false;
}
}
return $this->conn;
}
function disconnect() {
if ($this->conn) {
$this->conn = null;
}
}
function getOne($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetch();
return $reponse;
}
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
function execute($query) {
if (!$response = $this->conn->exec($query)) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
return $response;
}
}
and index.php has at the top above <!doctype
<?PHP
include('db.class.php');
$bdd = new db();
?>
along my html code
You just created an instance of this class, this only triggered the constructor, you did not make any calls to functions, so nothing shows on that page.
For the future: enable displaying errors by adding
ini_set('display_errors',1);
this will help you to find and correct errors.

PDO query doesn't work

I can't do a query.
This is my code, where I connect to database and try to query.
EDIT :
class DatabaseConnection {
private $host;
private $port;
private $dbname;
private $username;
private $password;
private $query;
function __construct($host, $port, $dbname, $username, $password) {
$this->host = $host;
$this->port = $port;
$this->dbname = $dbname;
$this->username = $username;
$this->password = $password;
try {
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
echo "PDO connection object created";
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
function setQuery($query) {
$this->query = $query;
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
}
}
$db = new DatabaseConnection('144.76.6.45','5432','eu','eu','eu123');
$db->setQuery('SELECT * FROM user');
This is my code, I don't have any errors, but still it doesn't work.....
Depending on the type of query you will want to fetch data after executing it. Take a look at fetch() and fetchAll() methods.
$sth = $db->prepare($this->query);
$sth->execute();
$result = $sth->fetchAll();
var_dump($result);
or use a loop and fetch row by row
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
var_dump($row);
}
after your edit:
Try to replace:
$conn = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
with
$this->db = new PDO("pgsql:host=$this->host port=$this->port dbname=$this->dbname", "$this->username", "$this->password");
and then call prepare method on it: $sth = $this->db->prepare($this->query); instead of $sth = $db->prepare($this->query);

Categories