I have a PHP program that connect to a MariaDB databse.
I upload name as "numbers" and i defined the value as UNIQUE so I donĀ“t want to be repeatated.
However I would like to handle the error when a vlaue is repeated:
This is the table I created:
Table in MariaDB
create table test(
-> id int NOT NULL AUTO_INCREMENT,
-> name varchar(255) UNIQUE,
-> date DATE NOT NULL,
-> PRIMARY KEY (id)
-> );
This is the script in PHP:
$host = "localhost";
$db_name = "xxx";
$username = "xxx";
$password = "xxx";
$connection = null;
$dt1=date("Y-m-d");
try{
$connection = new PDO("mysql:host=" . $host . ";dbname=" . $db_name, $username, $password);
$connection->exec("set names utf8");
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
function saveData($name, $dt1){
global $connection;
$query = "INSERT INTO test(name, date) VALUES( :name, :date )";
$callToDb = $connection->prepare( $query );
$name=htmlspecialchars(strip_tags($name));
//$dt1=htmlspecialchars(strip_tags($dt1));
$callToDb->bindParam(":name", $name);
$callToDb->bindParam(":date", $dt1);
if($callToDb->execute()){
//return '<h3 style="text-align:center;">registration submmited!</h3>';
//if (!$callToDb->execute()) {
// if ($callToDb->errno == 1062) {
// return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
// }
// else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
// }
}
}
if( isset($_POST['submit'])) {
$name = htmlentities($_POST['name']);
$dt1 = htmlentities($_POST['date']);
//then you can use them in a PHP function.
$result = saveData($name, $dt1);
echo $result;
}
else{
echo '<h3 style="text-align:center;">A very detailed error message</h3>';
}
//header("location:javascript://history.go(-1)");
}
the code part after if($callToDb->execute()){ it is commented because it is not working but I would like to just show a message when the vlaue is repeated. The same than when a vlaue is registrated correctly.
The issue to handle duplicate error is in this part which at the moment I am not using in my code as is not working fine:
if (!$callToDb->execute()) {
if ($callToDb->errno == 1062) {
return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
}
else{
return '<h3 style="text-align:center;">registration submmited!</h3>';
}
}
Any idea why this part of the code it is not working?
Change your code with this one.
$affected_rows = $callToDb->rowCount();
if (!$callToDb->execute())
{
if ($affected_rows == 0)
{
return '<h3 style="text-align:center;">VALUE REPEATED!</h3>';
}
else
{
return '<h3 style="text-align:center;">registration submmited!</h3>';
}
}
Related
I keep getting the error "SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" when using the UPDATE function in my php, even when my blindValues match the statement variables - I can't see where the error is in my syntax. Any help would be much appreciated as am new to php and this is part of an assessment. Thank you!
if (isset($_POST["Update"])) {
updateTEAM($_POST["ID"]);
}
function updateTEAM($id) {
try {
$conn = new PDO("mysql:host=" . $GLOBALS['servername'] . ";dbname=e0908659_OFA", $GLOBALS['username'], $GLOBALS['password']);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare("UPDATE TEAM SET ID=:id, TeamName=:teamname, Logo=:logo WHERE ID=". $id);
$statement->bindValue(":id", $_POST["ID"]);
$statement->bindValue(":teamname", $_POST["TeamName"]);
$statement->bindValue(":logo", $_POST["Logo"]);
$result = $statement->execute();
if ($result) {
$GLOBALS['message'] = "Team record was updated";
} else {
$GLOBALS['message'] = "The Team record was not updated";
}
}
catch(PDOException $e) {
echo "A problem occured: " . $e->getMessage();
}
$conn = null;
}
I can't reproduce the error, but I reproduced your file and database and created a supposed POST. I updated with success !.
I believe this is some incorrect information coming from your POST
My file .php
<?php
ini_set('display_errors',1);
ini_set('display_startup_erros',1);
error_reporting(E_ALL);
$_POST["ID"] = "123";
$_POST["TeamName"] = "Palmeiras";
$_POST["Logo"] = "palmeiras.jpg";
updateTEAM('12');
function updateTEAM($id) {
try {
$conn = new PDO("mysql:host=localhost;dbname=e0908659_OFA", 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare("UPDATE TEAM SET ID=:id, TeamName=:teamname, Logo=:logo WHERE ID=". $id);
$statement->bindValue(":id", $_POST["ID"]);
$statement->bindValue(":teamname", $_POST["TeamName"]);
$statement->bindValue(":logo", $_POST["Logo"]);
$result = $statement->execute();
if ($result) {
echo "Team record was updated";
} else {
echo "The Team record was not updated";
}
}
catch(PDOException $e) {
echo "A problem occured: " . $e->getMessage();
}
$conn = null;
}
And my sql
CREATE TABLE `team` (
`ID` INT(11) NULL DEFAULT NULL,
`TeamName` VARCHAR(50) NULL DEFAULT NULL,
`Logo` VARCHAR(50) NULL DEFAULT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
INSERT INTO team (ID, TeamName, Logo) VALUES (12, 'Corinthians', 'corinthians.jpg');
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);
I'm brand new to the world of databases... I'm trying to connect to the twitter API from a search query and than post the results to a database in mysql (creating the database in the process if no database exists)... I apologize if my code is kind of scattered and fragmented, this is a group project for a class and my group isn't exactly the cleanest of coders... Any ideas/thoughts or pointing out anything that seems to be done incorrectly would be a huge help. Thanks...
After typing in a query, this is the error received:
The twitter
Database does not exist. Creating it now ....
Warning: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045] Access denied for user 'root'#'localhost' (using password: YES)' in C:\xampp\htdocs\TwitterDB\database\database.php:17 Stack trace: #0 C:\xampp\htdocs\TwitterDB\database\database.php(17): PDO->__construct('mysql:host=loca...', 'root', 'sesame') #1 C:\xampp\htdocs\TwitterDB\searchDB.php(8): Database->__construct('twitter') #2 {main} thrown in C:\xampp\htdocs\TwitterDB\database\database.php on line 17
Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\TwitterDB\database\database.php on line 17
This is my database.php
class Database {
var $db;
public function __construct($dbname) {
$dsn = 'mysql:host=localhost;dbname=' .$dbname;
$username = 'root';
$password = 'sesame';
try {
$this ->db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo '<br> The <b>' .$dbname . '<br> Database does not exist. Creating it now .... <b>';
try {
$this ->db = new PDO('localhost', $username, $password);
$sql = "create database twitter;
use twitter;
create table tweets(
id VARCHAR(30) NOT NULL,
date dateTime,
from_user_id INT,
from_user_name VARCHAR(30),
to_user_id INT,
to_user_name VARCHAR(30),
geo VARCHAR(30),
profile_image_url VARCHAR(200),
text VARCHAR(150),
PRIMARY KEY (id, date, from_user_id)
)";
$this ->db ->exec($sql);
echo 'Done!<br>';
} catch (PDOException $e) {
echo $e ->getMessage();
exit();
}
}
}
public function close() {
try {
$this ->db - null;
} catch (PDOException $e) {
echo $e ->getMessage() . "Exit!";
exit();
}
}
public function insertTweets($tweets) {
$sql = "INSERT INTO TWEETS
(id, date, from_user_id, from_user_name, profile_image_url, text)
VALUES (:id, :date, :from_user_id, :from_user_name, :profile_image_url, :text)";
try {
$x = $this ->db ->prepare($sql);
foreach($tweets as $t) {
$parameters = array(
':id'=> $t ->id,
':date'=> date('Y-m-d- H:i:s', strtotime($t ->date)),
':from_user_id'=> $t ->from_user_id,
':from_user_name'=> $t ->from_user_name,
':profile_image_url'=> $t ->profile_image_url,
':text'=> $t ->text
);
$x ->execute($parameters);
}
} catch (PDOException $e) {
die ('Insert attempt failed:' . $e -> getMessage());
}
}
public function clearTable() {
try {
$x = $this ->db ->prepare('TRUNCATE TABLE tweets');
$x = execute();
} catch (PDOException $e) {
die('Attempt failed:' . $e ->getMessage());
}
}
public function search($query) {
try {
$x = $this ->db ->prepare($query);
$x -> execute();
} catch (PDOException $e) {
die ('Query failed:' . $e -> getMessage());
}
echo '<table border = 1>';
$heading = true;
while ( ($row = $x -> fetch(PDO::FETCH_ASSOC))) {
echo '<tr>';
if ($heading) {
$keys = array_keys($row);
foreach ($keys as $k) {
echo '<th>' .$k . '<th>';
}
echo '</tr><tr>';
$heading = false;
}
foreach($row as $r => $v) {
echo '<td>' . $v . '</td>';
}
echo '</tr>';
}
echo '</table>';
}
}
This is my insertDB.php
<?php
ini_set('display_errors', 1);
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "3219120843-cvff5Rj8LeFnmm6aM2eSdWN7bEKRwmjnJW64Wms",
'oauth_access_token_secret' => "MZS2Om2TRr9e56fgLAjWx7iwX3n7Svz18ya5iAXyWeMQS",
'consumer_key' => "y4sArn9Zl4DaA8KTPLIxFXVh8",
'consumer_secret' => "5Yj9soIQtLoQqbiXIgo1PhMSvI5sExsg13REHWGa1pPTzhTr2p"
);
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q='.$_POST['keyword'];
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$result = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$tweets = json_decode($result);
$tweet = $tweets->statuses;
echo $result;
require 'data_model.php';
$records = tweets2array($tweet);
require 'view.php';
echo tweet_obj_array2table($records);
$tweets = json_decode($result)->results;
$objects = tweets2array($tweets);
echo 'Total tweets:' . count($objects);
$database = new Database('twitter');
$table = 'tweets';
$database -> insertTweets($objects);
$database -> close();
?>
And this is my datamodel.php
<?php
function tweets2array($tweets) {
$records = array();
foreach($tweets as $tweet) {
$t = new stdClass();
$t->sender = $tweet->user->name;
$t->text = $tweet->text;
$t->time = $tweet->created_at;
$t->image = $tweet->user->profile_image_url;
$records[] = $t;
}
return $records;
}
?>
It appears that your database credentials do not have the right permissions to your database. I would recommend validating them again and the flushing the privileges. This should resolve the issue.
I have an admin store dashboard with an update button that triggers a php file which empties a mySQL database that then puts in new data from three .txt files (they are new stores). There is an issue where the table just gets wiped and/or the data from the .txt file is not being sent. I recently upgraded my PHP to 5.4 from 5.3 and am unsure what the issue is. Can anyone recommend me a suggestion on how to fix this issue?
PHP:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn = 'mysql:dbname=busaweb_stores;host=127.0.0.1';
$dsn_training = 'mysql:dbname=busaweb_busaedu;host=127.0.0.1';
$user = 'busaweb_*****';
$password = '*****';
try {
$dbs = new PDO($dsn, $user, $password);
$dbt = new PDO($dsn_training, $user, $password);
$dbs->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
catch (PDOException $e) {
die_with_error('PDO Connection failed: ' . $e->getMessage());
}
//Check request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "move":
move_files();
echo_success("Files have been moved.");
break;
case "update-stores":
$count = update_stores_db($dbs);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "geocode":
$count = geocode_remaining($dbs);
echo_success($count . " stores geocoded.");
break;
case "update-training":
update_training_db($dbt);
echo_success("Training DB Updated.");
break;
case "update-all":
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "backup":
$backupFile = backup_db();
echo_success("DB Backed Up: <br>" . $backupFile);
break;
default:
//Close PDO Connections
$dbs = null;
$dbt = null;
break;
}
}
}
//if being executed from the shell, update all
else if($totalArgv > 0){
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
};
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
//Error handling
function die_with_error($error) {
$return = array(
"status" => "Failed",
"data" => $error
);
//Close PDO Connections
$dbs = null;
$dbt = null;
die(json_encode($return));
}
function echo_success($message){
$return = array(
"status" => "OK",
"data" => $message
);
$return["json"] = json_encode($return);
echo json_encode($return);
//Close PDO Connections
$dbs = null;
$dbt = null;
}
//Move all files
function move_files(){
try {
move_file('sfinder/StoreList.txt');
move_file('sfinder/StoreProductIndex.txt');
move_file('sfinder/StoreTypeIndex.txt');
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
echo json_encode($return);
}
//Move a file
function move_file($filename){
$source ="/home/busaweb/public_html/b3/" . $filename;
$dest = "/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
//Empty a SQL Table
function empty_table($dbconnection, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconnection->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
//Import CSV file from JDE to DB
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_stores_db($dbs){
move_files();
empty_table($dbs, "stores");
load_csv($dbs, 'sfinder/StoreList.txt', 'stores');
empty_table($dbs, 'stores_product_type_link');
load_csv($dbs, 'sfinder/StoreProductIndex.txt', 'stores_product_type_link');
empty_table($dbs, 'stores_store_type_link');
load_csv($dbs, 'sfinder/StoreTypeIndex.txt', 'stores_store_type_link');
return $count;
}
function update_training_db($dbt){
move_file('training/TrainingCustomerList.txt');
empty_table($dbt, 'customers');
load_csv($dbt, 'training/TrainingCustomerList.txt', 'customers');
}
}
?>
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