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
Related
This code from my PHP Project.
and create oracle connection class.
modified from mysql connection class(work fine).
class databaseOracle
{
public $oci;
public $connected = false;
public $parameters;
public $result;
function __construct($host, $dbPort, $dbName, $userDB, $passwordDB)
{
try {
$ociDB = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host . ")(PORT = " . $dbPort . ")))(CONNECT_DATA=(SID=" . $dbName . ")))";
$this->oci = oci_connect($userDB, $passwordDB, $ociDB, 'AL32UTF8');
if (!$this->oci) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
echo "Database oracle connection Failed.</br>";
exit();
} else {
echo "Database oracle connection success.</br>";
}
} catch (EngineExcpetion $e) {
echo "Error : " . $e->getMessage() . "</br>";
}
// exit();
}
public function bind($para, $value)
{
$this->parameters[count($this->parameters)] = ":" . $para . "\x7F" . $value;
}
public function bindParams($parray)
{
if (empty($this->parameters) && is_array($parray)) {
$columns = array_keys($parray);
foreach ($columns as $i => &$column) {
$this->bind($column, $parray[$column]);
}
}
}
public function queryString($showQuery = 0, $query = "", $parameters = "")
{
$this->result = null;
if ($showQuery == 1) {
require_once('SQLFormatter.php');
echo SqlFormatter::format($query);
var_dump($parameters);
}
$this->result = oci_parse($this->oci, $query);
# Add parameters to the parameter array
$this->bindParams($parameters);
# Bind parameters
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("\x7F", $param);
oci_bind_by_name($this->result, $parameters[0], $parameters[1]);
}
}
oci_execute($this->result);
$r = oci_fetch_array($this->result, OCI_ASSOC + OCI_RETURN_LOBS + OCI_RETURN_NULLS);
$this->parameters = array();
return $r;
}
}
$oracleDB = new databaseOracle($ociHost, $ociPort, $ociDB, $ociUsername, $ociPassword);
$query = $oracleDB->queryString(0,"SELECT * from SOME_TABLE where CREATED_BY = :created FETCH NEXT 50 ROWS ONLY",array("created" => "2"));
print_r($query);
my problem
i'm create class of oracle connection. modify from mysql connection class.
it's can query and read record from oracle database. example 50 record
but array result of query show first row only.
How is everything
Please can anyone help me in this
I'm trying to use PHP PDO transaction and there is a problem that I face and I can't deal with it.
rollBack function doesn't work when It catch an exception
Here is the connection code
$host = 'localhost';
$user = 'root';
$pass = '';
$error = '';
$dbname = 'tameras_finance';
// Set DSN
$dsn = 'mysql:host=' . $host . '; dbname=' . $dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->exec("set names utf8");
}
//Catch any errors
catch (PDOException $e) {
echo $error = $e->getMessage();
}
and here the code
try{
$dbh->beginTransaction();
$dbh->query('SET #newDebit = (SELECT max(`debtor_id`) + 1 AS maxDebit FROM `vocher`)');
for($x = 0; $x < count($debits); $x++){
$dbh->query('UPDATE `vocher` SET `debtor_id` = #newDebit, `status_id` = "4" WHERE `id` = '.$debits[$x]);
}
for($x = 0; $x < count($others); $x++){
$columns = '`acc_id`, `value`, `date`, `desc`, `reject`, `vo_type_id`, `user`, `debtor_id`';
$vals = "'".$accs[$x]."','".$values[$x]."','".$dates[$x]."','".$descs[$x]."','1','1','".$user."', #newDebit";
if($others[$x] == 'e'){
$columns .= ', `cheque_no`, `available_date`, `issue_date`, `bank_id`';
$vals .= ", '".$sns[$x]."', '".$availdates[$x]."', '".$issueDates[$x]."', '".$banks[$x]."'";
}
$dbh->query("INSERT INTO creditor (".$columns.") VALUES (".$vals.")");
if($lists[$x] != 'e'){
$lastId = $dbh->lastInsertId();
$q = 'INSERT INTO `creditor_cc` (`creditor`, `cc`) VALUES ';
for($y = 0; $y < count($lists[$x]); $y++){
$dif = count($lists[$x]) - $y;
$q .= '(';
$q .= '"' . $lastId . '",';
$q .= '"'.$lists[$x][$y].'"';
$q .= ')';
if($dif > 1){
$q .= ',';
}
}
$dbh->query($q);
}
}
$dbh->commit();
} catch(PDOException $e) {
echo $error = $e->getMessage();
$dbh->rollBack();
}
This code doesn't rollback
Please note that:
$sns, $others, $accs, $values, $dates, $descs, $availdates,
$issueDates and $banks are arrays with the same size
Also $lists is a two dimension array with the same size
please help me with this why this code doesn't rollBack
Transactions are not supported on MySQL's default table type MyISAM. You need to make sure you're using InnoDB tables.
Also check to make sure the exception that's being thrown is PDOException or it'll fall through the try/catch and not hit your rollback.
I would say it shoud be done this way:
$pdo = new \PDO(/*...*/);
$pdo->beginTransaction();
try {
//...
} catch(\Exception $e) {
$pdo->rollBack();
throw $e;
}
$pdo->commit();
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);
How is everything
Please can anyone help me in this
I'm trying to use PHP PDO transaction and there is a problem that I face and I can't deal with it.
rollBack function doesn't work when It catch an exception
Here is the connection code
$host = 'localhost';
$user = 'root';
$pass = '';
$error = '';
$dbname = 'tameras_finance';
// Set DSN
$dsn = 'mysql:host=' . $host . '; dbname=' . $dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
$dbh = new PDO($dsn, $user, $pass);
$dbh->exec("set names utf8");
}
//Catch any errors
catch (PDOException $e) {
echo $error = $e->getMessage();
}
and here the code
try{
$dbh->beginTransaction();
$dbh->query('SET #newDebit = (SELECT max(`debtor_id`) + 1 AS maxDebit FROM `vocher`)');
for($x = 0; $x < count($debits); $x++){
$dbh->query('UPDATE `vocher` SET `debtor_id` = #newDebit, `status_id` = "4" WHERE `id` = '.$debits[$x]);
}
for($x = 0; $x < count($others); $x++){
$columns = '`acc_id`, `value`, `date`, `desc`, `reject`, `vo_type_id`, `user`, `debtor_id`';
$vals = "'".$accs[$x]."','".$values[$x]."','".$dates[$x]."','".$descs[$x]."','1','1','".$user."', #newDebit";
if($others[$x] == 'e'){
$columns .= ', `cheque_no`, `available_date`, `issue_date`, `bank_id`';
$vals .= ", '".$sns[$x]."', '".$availdates[$x]."', '".$issueDates[$x]."', '".$banks[$x]."'";
}
$dbh->query("INSERT INTO creditor (".$columns.") VALUES (".$vals.")");
if($lists[$x] != 'e'){
$lastId = $dbh->lastInsertId();
$q = 'INSERT INTO `creditor_cc` (`creditor`, `cc`) VALUES ';
for($y = 0; $y < count($lists[$x]); $y++){
$dif = count($lists[$x]) - $y;
$q .= '(';
$q .= '"' . $lastId . '",';
$q .= '"'.$lists[$x][$y].'"';
$q .= ')';
if($dif > 1){
$q .= ',';
}
}
$dbh->query($q);
}
}
$dbh->commit();
} catch(PDOException $e) {
echo $error = $e->getMessage();
$dbh->rollBack();
}
This code doesn't rollback
Please note that:
$sns, $others, $accs, $values, $dates, $descs, $availdates,
$issueDates and $banks are arrays with the same size
Also $lists is a two dimension array with the same size
please help me with this why this code doesn't rollBack
Transactions are not supported on MySQL's default table type MyISAM. You need to make sure you're using InnoDB tables.
Also check to make sure the exception that's being thrown is PDOException or it'll fall through the try/catch and not hit your rollback.
I would say it shoud be done this way:
$pdo = new \PDO(/*...*/);
$pdo->beginTransaction();
try {
//...
} catch(\Exception $e) {
$pdo->rollBack();
throw $e;
}
$pdo->commit();
I am working on an app that needs to select data from a MySQL database. I am currently testing the PHP script via my browser to make sure that it is returning the correct data. The issue is currently it returns the exception "Database Error!". I have included my PHP script.
get_agencies_by_city.php
<?php
/*
* Following code will get all agencies matching the query
* Returns essential details
* An agency is identified by agency id
*/
require("DB_Link.php");
$city = ($_GET['City']);
//query database for matching agency
$query = "SELECT * FROM agency WHERE City = $city";
//Execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
//Retrieve all found rows and add to array
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Agency found!";
die(json_encode($response));
}
?>
Here is the DB_Link.php
<?php
// These variables define the connection information the MySQL database
// set connection...
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
You should rewrite your query to this, as it is a prepared statement and your query will be much safer (and working)!
//your code
try {
$statement = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$statement->execute(array('city' => $city));
// rest of your code
}
// and the exception
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
also you should check if $_GET really is set!
LIKE THIS:
try {
$stmt = $dbh->prepare("SELECT * FROM agency WHERE city = :city");
$stmt->execute(array('city' => $city));
$rows = $stmt->FETCHALL();
if($rows) {
$response["success"] = 1;
$response["message"] = "Results Available!";
$response["agencys"] = array();
foreach ($rows as $row) {
$agency = array();
$agency["AgencyID"] = $row["AgencyID"];
$agency["AgencyName"] = $row["AgencyName"];
$agency["Address1"] = $row["Address1"];
$agency["City"] = $row["City"];
$agency["State"] = $row["State"];
$agency["Zip"] = $row["Zip"];
$agency["Lat"] = $row["Lat"];
$agency["Lon"] = $row["Lon"];
//update response JSON data
array_push($response["agencys"], $agency);
}
//Echo JSON response
echo json_encode($response);
} }
catch (PDOException $ex) {
//or include your error statement - but echo $ex->getMessage()
die('Error!: ' . json_encode($ex->getMessage()));
}
The variable $city needs to be in your query. Do something like this:
$query = "SELECT * FROM Agency WHERE City = " . $city;