How can I verify successful row creation (and modification) when using prepared_insert in PDO?
Here is my code:
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
$data = array_filter($data);
//var_dump ($data);
prepared_insert($conn, 'products', $data);
$id = $conn->lastInsertId();
if ($id > 0) {
echo json_encode(array('response'=>'success','message'≥'Row successfully added'));
}else{
echo json_encode(array('response'=>'danger','message'≥'Row not successfully added'));
}
}catch(PDOException $e){
echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
$conn = null;
As you can see, right now I am doing it by using lastInsertId() but I do not think that's the correct way to do it.
Additionally, if the row was not created, how can I capture the error behind it and report it?
you not need create this condition :
if ($id > 0) {
echo json_encode(array('response'=>'success','message'≥'Row successfully added'));
}else{
echo json_encode(array('response'=>'danger','message'≥'Row not successfully added'));
}
because you using try and catch.. you can make sure it with database transaction.. try to commit and catch to rollback..
Related
I have a PDO with a dynamically created statement, I am running into errors when I try to insert empty data into decimal fields, I believe the issue is I need input null instead of empty. Here is my code:
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
prepared_insert($conn, 'products', $data);
$id = $conn->lastInsertId();
if ($id > 0) {
echo json_encode(array('response'=>'success'));
}else{
echo json_encode(array ('response'=>'error','errorMessage'=>'Row not created'));
}
}catch(PDOException $e){
echo json_encode(array ('response'=>'error','errorMessage'=>$e->getMessage()));
}
$conn = null;
How can I make this insert null instead of empty?
Change your table settings. Set it to accept null in that column:
ALTER TABLE `table` CHANGE `column` `column` VARCHAR(255) NULL DEFAULT NULL;
Forgive me if the question is a little odd
I can clarify if needed:
I have the code that can connect to a mysql database as normal, however i have encapsulated it as a class:
<?php
define("HOST", "127.0.0.1"); // The host you want to connect to.
define("USER", "phpuser"); // The database username.
define("PASSWORD", "Secretpassword"); // The database password.
class DBConnection{
function conn($sql, $database){
$DB = new mysqli(HOST,USER,PASSWORD,$database);
if ($DB->connect_error){
die("Connection failed: " . $DB->connect_error);
exit();
}
if ($result = $DB->query($sql)){
return TRUE;
$DB->close();
}
else{
echo "Error: " . $sql . "<br>" . $DB->error;
$DB->close();
}
}
}
?>
I have done it this way so i can include this class in any subsequent php page and allow them to send it an sql statment and the database, see below as an example:
$sql = ("INSERT INTO users (first_name, last_name, username, email, password, group_level) VALUES ('John', 'Doah','JDoah', 'example#email', 'password', 'user')");
$DB = new DBConnection;
$result = $DB->conn($sql,"members");
if ($result ==TRUE){
return "Record added sucessfully";
}
This works fine.
however, im looking to send other sql statments to DBConnection.
How do i do that and to have it pass back any results that it recives? errors, boolean, row data etc. The caller will worry about parsing it.
Hopefully that makes sense.
This is an old class I used to use way back in the days of mysql still works but will need to be updated for mysqli or newer
class DBManager{
private $credentials = array(
"host" => "localhost",
"user" => "",
"pass" => "",
"db" => ""
);
function DBManager(){
$this->ConnectToDBServer();
}
function ConnectToDBServer(){
mysql_connect($this->credentials["host"],$this->credentials["user"],$this->credentials["pass"]) or die(mysql_error());
$this->ConnectToDB();
session_start();
}
function ConnectToDB(){
mysql_select_db($this->credentials["db"]) or die(mysql_error());
}
function Insert($tableName,$data){
$parameters = '';
$len = count($data);
$i = 0;
foreach($data as $key => $value){
if(++$i === $len){
$parameters .= $key . "='$value'";
}else{
$parameters .= $key . "='$value'" . ", ";
}
}
$query = "INSERT INTO $tableName SET $parameters";
mysql_query($query) or die(mysql_error());
return true;
}
function GetRow($tableName,$select,$where){
$selection = '';
$len = count($select);
$i = 0;
foreach($select as $key){
if(++$i === $len){
$selection .= $key;
}else{
$selection .= $key . ",";
}
}
$whereAt = '';
foreach($where as $key => $value){
$whereAt .= $key . "='$value'";
}
$query = "SELECT $selection FROM $tableName WHERE $whereAt";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
return $row;
}
}
}
The key things here is you can create a persistent connection to your database without rewriting a bunch of code
Example
global $DB;
$DB = new DBManager();
Since the connection happens in the constructor you will now have a connection on the page you call this code and can begin getting and setting to the database through use of $DB->GetRow() and $DB->Insert() which makes things much easier and was modeled after the $wpdb instance which is a class that manages the database in wordpress sites
Examples
For these examples we will assume you have a table as such
Insert new student
//create an associative array
$data = array(
"student_id" => 1,
"birth_date" => "02/06/1992",
"grade_level" => 4
);
//Send Call
$dm->Insert("student",$data);
Get data
//Create selection
$selection = array("grade_level");
//Create associative array for where we want to find the data at
$where = array(
"id" => 1
);
//Get Result
$result = $dm->GetRow("student",$selection,$where);
//do something with result
echo $result->grade_level;
I have a custom class that takes a sql connection as a parameter. I use that to populate the class, and then I'm trying to use it again to modify the results on screen. But after the first use, I can't use it anymore.
connection.php:
$conn = new mysqli('localhost', 'root', '', 'loveConnections');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
personalityProfile.php (front end)
if (!isset($_SESSION['interests'])) {
$interests = new Interests($conn, $_SESSION['id']);
$_SESSION['interests'] = $interests;
} else {
$interests = $_SESSION['interests'];
}
interestsObject.php
class Interests {
// properties
public $conn;
public $id;
public $interestsArray = [];
public function __construct($conn, $memberId = null, $intArray = [
'basketball' => false,
'bowling' => false,
'movies' => false,
]) {
$this->conn = $conn;
$this->id = $memberId;
$this->interestsArray = $intArray;
$this->popArraySql();
}
public function popArraySql() {
$memInterests = [];
$sql = "SELECT i.interest
FROM memberInfo m
Join MemberInterestLink mi on (mi.memberID_FK = m.memberID_PK)
Join interests i on (mi.interestID_FK = i.interestID_PK)
WHERE memberID_PK = $this->id";
$result = $this->conn->query($sql);
$this->conn works perfectly here
foreach ($result as $row) {
array_push($memInterests, $row['interest']);
}
foreach ($this->interestsArray as $key => $value) {
for ($i=0; $i<sizeof($memInterests); $i++) {
if ($memInterests[$i] === $key) {
$this->interestsArray[$key] = true;
}
}
}
}
public function insertUpdateQuery() {
var_dump($this->conn);
foreach ($this->interestsArray as $key => $val) {
echo $key . "<br>";
$select = "SELECT interestID_PK from interests where interest = '" . $key . "'";
echo $select;
$result = $this->conn->query($select);
when I try and use it later though, I get a Warning: mysqli::query(): Couldn't fetch mysqli. Additionally, if I try and var_dump it, I get Warning: var_dump(): Property access is not allowed yet
var_dump($result);
if ($val === true) {
$insert = "INSERT INTO MemberInterestLink (memberID_FK, interestID_FK) VALUES ($this->id, $interestKey)";
$this->conn->query($insert);
} else {
$delete = "DELETE FROM MemberInterestLink WHERE interestID_FK = $interestKey";
$this->conn->query($delete);
}
}
}
}
I never close the connection, which is what most of the related answers suggested the cause may be. It's like my $conn variable just stops working after the first use.
I want to make a sendmail function on my program. But first, I want to store the information: send_to, subject, and message in a table in another database(mes) where automail is performed. The problem is data fetched from another database(pqap) are not being added on the table(email_queue) in database(mes).
In this code, I have a table where all databases in the server are stored. I made a query to select a specific database.
$sql5 = "SELECT pl.database, pl.name FROM product_line pl WHERE visible = 1 AND name='PQ AP'";
$dbh = db_connect("mes");
$stmt5 = $dbh->prepare($sql5);
$stmt5->execute();
$data = $stmt5->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
Then after selecting the database,it has a query for selecting the information in the table on the selected database. Here's the code.
foreach ($data as $row5) GenerateEmail($row5['database'], $row5['name']);
Then this is part (I think) is not working. I don't know what's the problem.
function GenerateEmail($database, $line) {
$sql6 = "SELECT * FROM invalid_invoice WHERE ID=:id6";
$dbh = db_connect($database);
$stmt6 = $dbh->prepare($sql6);
$stmt6->bindParam(':id6', $_POST['idtxt'], PDO::PARAM_INT);
$stmt6->execute();
$data = $stmt6->fetchAll(PDO::FETCH_ASSOC);
$dbh=null;
foreach ($data as $row6) {
$invnumb=$row6['Invoice_Number'];
$partnumb=$row6['Part_Number'];
$issue=$row6['Issues'];
$pic=$row6['PIC_Comments'];
$emailadd= $row6['PersoninCharge'];
if($row6['Status']=="Open") {
$message = "<html><b>Invoice Number: {$invnumb}.</b><br><br>";
$message .= "<b>Part Number:</b><br><xmp>{$partnumb}</xmp><br><br>";
$message .= "<b>Issues:</b><br><xmp>{$issue}</xmp><br>";
$message .= "<b>{$pic}<b><br>";
$message .= "</html>";
if(!empty($emailadd)) {
dbInsertEmailMessage($emailadd, "Invoice Number: {$invnumb} - {$issue}.", $message);
$dbh=null;
}
}
}
}
function dbInsertEmailMessage($send_to, $subject, $message) {
$sql7 = "INSERT INTO email_queue (Send_to, Subject, Message) VALUES (:send_to, :subject, :message)";
$dbh = db_connect("mes");
$stmt7 = $dbh->prepare($sql7);
$stmt7->bindParam(':send_to', $send_to, PDO::PARAM_STR);
$stmt7->bindParam(':subject', $subject, PDO::PARAM_STR);
$stmt7->bindParam(':message', $message, PDO::PARAM_STR);
$stmt7->execute();
$dbh=null;
}
Here's my db connection:
function db_connect($DATABASE) {
session_start();
// Connection data (server_address, database, username, password)
$servername = '*****';
//$namedb = '****';
$userdb = '*****';
$passdb = '*****';
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$dbh = new PDO("mysql:host=$servername; dbname=$DATABASE", $userdb, $passdb, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
return $dbh;
//echo 'Connected to database';
}
catch(PDOException $e) {
echo $e->getMessage();
}
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
There are a couple things that may help with your failed inserts. See if this is what you are looking for, I have notated important points to consider:
<?php
// take session_start() out of your database connection function
// it draws an error when you call it more than once
session_start();
// Create a connection class
class DBConnect
{
public function connect($settings = false)
{
$host = (!empty($settings['host']))? $settings['host'] : false;
$username = (!empty($settings['username']))? $settings['username'] : false;
$password = (!empty($settings['password']))? $settings['password'] : false;
$database = (!empty($settings['database']))? $settings['database'] : false;
try {
$dbh = new PDO("mysql:host=$host; dbname=$database", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// You return the connection before it hits that setting
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
catch(PDOException $e) {
// Only return the error if an admin is logged in
// you may reveal too much about your database on failure
return false;
//echo $e->getMessage();
}
}
}
// Make a specific connection selector
// Put in your database credentials for all your connections
function use_db($database = false)
{
$con = new DBConnect();
if($database == 'mes')
return $con->connect(array("database"=>"db1","username"=>"u1","password"=>"p1","host"=>"localhost"));
else
return $con->connect(array("database"=>"db2","username"=>"u2","password"=>"p2","host"=>"localhost"));
}
// Create a query class to return selects
function query($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return (!empty($result))? $result:0;
}
// Create a write function that will write to database
function write($con,$sql,$bind=false)
{
if(empty($bind))
$query = $con->query($sql);
else {
foreach($bind as $key => $value) {
$kBind = ":{$key}";
$bindVals[$kBind] = $value;
}
$query = $con->prepare($sql);
$query->execute($bindVals);
}
}
// Do not create connections in your function(s), rather pass them into the functions
// so you can use the same db in and out of functions
// Also do not null the connections out
function GenerateEmail($con,$conMes,$line = false)
{
if(empty($_POST['idtxt']) || (!empty($_POST['idtxt']) && !is_numeric($_POST['idtxt'])))
return false;
$data = query($con,"SELECT * FROM `invalid_invoice` WHERE `ID` = :0", array($_POST['idtxt']));
if($data == 0)
return false;
// Instead of creating a bunch of inserts, instead create an array
// to build multiple rows, then insert only once
$i = 0;
foreach ($data as $row) {
$invnumb = $row['Invoice_Number'];
$partnumb = $row['Part_Number'];
$issue = $row['Issues'];
$pic = $row['PIC_Comments'];
$emailadd = $row['PersoninCharge'];
if($row['Status']=="Open") {
ob_start();
?><html>
<b>Invoice Number: <?php echo $invnumb;?></b><br><br>
<b>Part Number:</b><br><xmp><?php echo $partnumb; ?></xmp><br><br>
<b>Issues:</b><br><xmp><?php echo $issue; ?></xmp><br>
<b><?php echo $pic; ?><b><br>
</html>
<?php
$message = ob_get_contents();
ob_end_clean();
if(!empty($emailadd)) {
$bind["{$i}to"] = $emailadd;
$bind["{$i}subj"] = "Invoice Number: {$invnumb} - {$issue}.";
$bind["{$i}msg"] = htmlspecialchars($message,ENT_QUOTES);
$sql[] = "(:{$i}to, :{$i}subj, :{$i}msg)";
}
}
$i++;
}
if(!empty($sql))
return dbInsertEmailMessage($conMes,$sql,$bind);
return false;
}
function dbInsertEmailMessage($con,$sql_array,$bind)
{
if(!is_array($sql_array))
return false;
write($con,"INSERT INTO `email_queue` (`Send_to`, `Subject`, `Message`) VALUES ".implode(", ",$sql_array),$bind);
return true;
}
// Create connections
$con = use_db();
$conMes = use_db('mes');
GenerateEmail($con,$conMes);
The function is pretty straightforward:
The variables: $table is the table which the update is taking place
and $fields are the fields in the table,
and $values are generated from a post and put into the $values array
and $where is the value of the id of the index field of the table
and $indxfldnm is the index field name
function SQLUpdate($table,$fields,$values,$where,$indxfldnm) {
//Connect to DB
$dbaddr = DB_HOST;
$dbusr = DB_USER;
$dbpwd = DB_PASSWORD;
$dbname = DB_DATABASE;
$db = new PDO('mysql:host='.$dbaddr .';dbname='.$dbname.';charset=UTF8', $dbusr, $dbpwd);
//build the fields
$buildFields = '';
if (is_array($fields)) {
//loop through all the fields
foreach($fields as $key => $field) :
if ($key == 0) {
//first item
$buildFields .= $field;
} else {
//every other item follows with a ","
$buildFields .= ', '.$field;
}
endforeach;
} else {
//we are only inserting one field
$buildFields .= $fields;
}
//build the values
$buildValues = '';
if (is_array($values)) {
//loop through all the values
foreach($values as $key => $value) :
if ($key == 0) {
//first item
$buildValues .= '?';
} else {
//every other item follows with a ","
$buildValues .= ', ?';
}
endforeach;
} else {
//we are only updating one field
$buildValues .= ':value';
}
$sqlqry = 'UPDATE '.$table.' SET ('.$buildFields.' = '.$buildValues.') WHERE `'.$indxfldnm.'` = \''.$where.'\');';
$prepareUpdate = $db->prepare($sqlqry);
//execute the update for one or many values
if (is_array($values)) {
$prepareUpdate->execute($values);
} else {
$prepareUpdate->execute(array(':value' => $values));
}
//record and print any DB error that may be given
$error = $prepareUpdate->errorInfo();
if ($error[1]) print_r($error);
echo $sqlqry;
return $sqlqry;
}
So far so good
However its not working
there is something wrong with transferring the values into the fields in a proper update statement
but I'm not so good with pdo and setting it up
a little help to fix the code to bind the parameters to the values in an update would
be greatly appreciated
Thank you
Try getting this in your function
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Changed Code to a different build:
This eliminated the multiple-value problem
function SQLUpdate($table,$fields,$values,$where,$indxfldnm) {
$dbdata = array();
$i=0;
foreach ($fields as $fld_nm)
{
if ($i > 0) {
$dbdata[$fld_nm] = $values[$i]; }
$i++;
} //end foreach
$buildData = '';
foreach ($dbdata as $key => $val) {
if (empty($val)) {$buildData .= '`'.$key.'` = \'NULL\', ';} else {
$buildData .= '`'.$key.'` = \''.$val.'\', ';}
}
$buildData = substr($buildData,0,-2);
$dbaddr = DB_HOST;
$dbusr = DB_USER;
$dbpwd = DB_PASSWORD;
$dbname = DB_DATABASE;
$prepareUpdate ='';
try {
$db = new PDO('mysql:host='.$dbaddr .';dbname='.$dbname.';charset=UTF8', $dbusr, $dbpwd);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET CHARACTER SET utf8");
$sqlqry = 'UPDATE '.$table.' SET '.$buildData.' WHERE `'.$indxfldnm.'` = \''.$where.'\';';
$prepareUpdate = $db->exec($sqlqry);
//execute the update for one or many values
}
catch(PDOException $e)
{
$e->getMessage();
print_r($e);
}
return $sqlqry;
}
//END: SQLUpdate