I'm using ADODB and MYSQL, trying to execute an INSERT statement.
Though I've read plenty of forum posts and learned that I cannot bind parameters as easily as with oci8, I still have not found an example similiar to what I'm trying to achieve. My code is as follows with oci8:
$street = $branch->getStreet();
$number = $branch->getNumber();
$city = $branch->getCity();
$state = $branch->getState();
$xMap = $branch->getXMap();
$yMap = $branch->getYMap();
$email = $branch->getEmail();
try{
//$this->db->debug = true;
$sql = "INSERT INTO branch ( nombre_branch, street, number, city, state, x_map, y_map, email ) VALUES (:branchName, :street, :number, :city, :state, :xMap, :yMap, :email)";
$sp = $this->db->PrepareSP($sql);
$this->db->InParameter($sp, $branchName, 'branchName');
$this->db->InParameter($sp, $street, 'street');
$this->db->InParameter($sp, $number, 'number');
$this->db->InParameter($sp, $city, 'city');
$this->db->InParameter($sp, $state, 'state');
$this->db->InParameter($sp, $xMap, 'xMap');
$this->db->InParameter($sp, $yMap, 'yMap');
$this->db->InParameter($sp, $email, 'email');
$rs = $this->db->Execute($sp);
} catch(ADODB_Exception $adodb_exception){
$logInfo['exception'] = $adodb_exception->getMessage();
$message = "'[".__CLASS__."] Error al executing ' insert '";
if( !$this->rollbackTransaction()){
if(!is_null($this->log)) $this->log->log("ERROR in DB: ".print_r($logInfo, true), PEAR_LOG_ERR);
$message .= " Error in ROLLBACK.";
throw new DAODatabaseTransactionException ($message, $adodb_exception->getCode());
}
}
return $returnValue;
}
Thanks!
This is how i got it to work with mysql, without having to implement PDO
$sql = "INSERT INTO branch( branch_name, street, number, city, state, x_map, y_map, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$rs = $this->db->Execute($sql, array($branchName, $street, $number, $city, $state, $xMap, $yMap, $email));
$rs->Close();
Related
I have an app that is written using procedural PHP. I've created an insert page where I take a buck of addresses and pass them as an array and insert them in the database. There I have the id of the row and then an orderId, the address type, and the address. Now I want to be able to update a specific one. Until now I've come up with the following:
// update new supplier order
function updateSupplierOrder($conn, $orderDate, $datePickup, $dateDelivery, $timePickup, $timeDelivery, $car, $carType, $goodsDescription, $paletChange, $paletNo, $supplier, $orderObservation, $paymentDate, $value, $addressPickup, $addressDelivery, $userid, $orderID) {
$sql1 = "UPDATE suppliersOrders SET supplierId = ?, date = ?, datePickup = ?, timePickup = ?, goodsDescription = ?, dateDelivery = ?, timeDelivery = ?, carType = ?, carNo = ?, paletChange = ?, paletNo = ?, value = ?, invoice = ?, observations = ?, operator = ? WHERE id = ?;";
$stmt1 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt1, $sql1)) {
header ("location: ../suppliersOrders?error=failedupdateorder");
exit();
}
mysqli_stmt_bind_param($stmt1, "isssssssisisssii", $supplier, $orderDate, $datePickup, $timePickup, $goodsDescription, $dateDelivery, $timeDelivery, $carType, $car, $paletChange, $paletNo, $value, $paymentDate, $orderObservation, $userid, $orderID);
mysqli_stmt_execute($stmt1);
mysqli_stmt_close($stmt1);
for ($i=0; $i<count($addressPickup); $i++) {
$address = $addressPickup[$i];
$type = '1';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
for ($i=0; $i<count($addressDelivery); $i++) {
$address = $addressDelivery[$i];
$type = '2';
$sql2 = "UPDATE suppliersOrdersAddress SET address = ?, operator = ? WHERE orderId = ? AND addressType = ?;";
$stmt2 = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt2, $sql2)) {
header ("location: ../suppliersOrders?error=failedupdateaddress");
exit();
}
mysqli_stmt_bind_param($stmt2, "siii", $address, $userid, $orderID, $type);
mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);
}
header("location: ../suppliersOrders-edit.php?id=$orderID");
}
But this will update all the addresses of an order and a type. How can I update based on the id from the table, this will make sure that the right address is updated.
Help would be appreciated.
I found a solution to the issues. The simplest way to be able to update the row that I needed was to add the id value from the row in an array and do the update based on the WHERE clause that had the id value. This way I was able to update just the needed value/row.
I have this code.
<?php
// open mysql connection
$host = "localhost";
$username = "root";
$password = "";
$dbname = "jacklin";
$con = mysqli_connect($host, $username, $password, $dbname) or die('Error in Connecting: ' . mysqli_error($con));
// use prepare statement for insert query
$st = mysqli_prepare($con, 'INSERT INTO company_details(com_name, city, com_address, com_mno, com_lno, com_faxno, com_email, com_url, contact_person, com_img,
lat, lng, cat_src_pos, state, country, password, status, plan, token, pin, contact_person1, contact_person2,
com_mno1, com_mno2, fpass_token, adv_src_pos, alias, com_skype, cover)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
// bind variables to insert query params
mysqli_stmt_bind_param($st, 'ssssssssssssissssssssssssisss', $id, $city, $com_address, $com_mno, $com_lno, $com_faxno, $com_email, $com_url, $contact_person, $com_img, $lat, $lng, $cat_src_pos, $state, $country, $password, $status, $plan, $token, $pin, $contact_person1, $contact_person2, $com_mno1, $com_mno2, $fpass_token, $adv_src_pos, $alias, $com_skype, $cover);
// read json file
$filename = 'empdata.json';
$json = file_get_contents($filename);
//convert json object to php associative array
$data = json_decode($json, true);
// loop through the array
foreach ($data as $row) {
// get the employee details
$id = $row['com_name'];
$city = $row['city'];
$com_address = $row['com_address'];
$com_mno = $row['com_mno'];
$com_lno = $row['com_lno'];
$com_faxno = $row['com_faxno'];
$com_email = $row['com_email'];
$com_url = $row['com_url'];
$contact_person = $row['contact_person'];
$com_img = $row['com_img'];
$lat = $row['lat'];
$lng = $row['lng'];
$cat_src_pos = $row['cat_src_pos'];
$state = $row['state'];
$country = $row['country'];
$password = $row['password'];
$status = $row['status'];
$plan = $row['plan'];
$token = $row['token'];
$pin = $row['pin'];
$contact_person1 = $row['contact_person1'];
$contact_person2 = $row['contact_person2'];
$com_mno1 = $row['com_mno1'];
$com_mno2 = $row['com_mno2'];
$fpass_token = $row['fpass_token'];
$adv_src_pos = $row['adv_src_pos'];
$alias = $row['alias'];
$com_skype = $row['com_skype'];
$cover = $row['cover']
// execute insert query
mysqli_stmt_execute($st);
}
//close connection
mysqli_close($con);
?>
and my empdata.json is like.
[{"com_id":"1","com_name":"SORENTO GRANITO PVT.LTD","city":"Morbi","com_address":"8-A National High WayOld ghuntu Road ,Morbi - 363 642 (Guj.) INDIA","com_mno":"+919377721600","com_lno":"02822 - 243783 \/ 84","com_faxno":"(02822) 243785","com_email":"marketing#sorentogranito.com","com_url":"www.sorentogranito.com","contact_person":"Mr. Bhagubhai Tulsiyani","com_img":"1403952411.png","lat":"22.824254","lng":"70.8606801","cat_src_pos":"400000","state":"Gujarat","country":"India","password":"91SORESGPL","status":"active","plan":"premium","token":"","pin":"363 642","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"400000","alias":"sorento-granito-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"3","com_name":"COTO CERAMIC PVT LTD","city":"Morbi","com_address":"8-A National Higway,B\/ h Makansar Panjarapore Weed...","com_mno":"+919099173713","com_lno":"+919099173713","com_faxno":"","com_email":"info#cotobathware.com","com_url":"www.cotobathware.com","contact_person":"Mr. SUMEET MARVANIYA","com_img":"d08687ba60bb3f0d1317e2fd8b10afd4.png","lat":"22.748123","lng":"70.9369573","cat_src_pos":"500000","state":"Gujarat","country":"India","password":"MAYANK8877","status":"active","plan":"basic","token":"","pin":"363621","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"500000","alias":"coto-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"4","com_name":"GLORY CERAMIC PVT LTD","city":"Morbi","com_address":"8\/A , National Highway Lalpar Morbi","com_mno":"+919825228848","com_lno":"02822 - 650445\/ 652446","com_faxno":"","com_email":"gloryceramic#yahoo.co.in","com_url":"www.gloryceramic.com","contact_person":"Mr. Niraj Thakkar","com_img":"1403952443.png","lat":"22.7968786","lng":"70.8907196","cat_src_pos":"80000","state":"Gujarat","country":"India","password":"9227650445","status":"active","plan":"premium","token":"","pin":"363 641","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"80000","alias":"glory-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"},{"com_id":"5","com_name":"SALON CERAMIC PVT.LTD.","city":"Morbi","com_address":"8-A National Highway, Olg Ghuntu Road, Morbi - 363 642(Guj.) INDIA","com_mno":"+91 9825223840","com_lno":"+91 2822 242115","com_faxno":"+91 2822 242116","com_email":"info#salonceramic.com","com_url":"www.salonceramic.com","contact_person":"Mr. Hiteshbhai","com_img":"1413397071.PNG","lat":"22.838649048614528","lng":"70.88279977525485","cat_src_pos":"400000","state":"Gujarat","country":"India","password":"123salon123","status":"active","plan":"premium","token":"252985240685b6f5b1728d0d31bc585b","pin":"363642","contact_person1":"","contact_person2":"","com_mno1":"","com_mno2":"","fpass_token":"","adv_src_pos":"400000","alias":"salon-ceramic-pvt-ltd","com_skype":"","cover":"motto.jpg"}]
with 1000 of records.but when i run above code in my localhost it's not displaying any error and not inserting any record to database too. please tell me how to insert this type json to database.
Try a simple foreach loop to count the number of data, and then make a for loop for running the insert statement:
$file = file_get_contents('empdata.json');
$json = json_decode($file, true);
//echo '<pre>';
//print_r($json);
$num = array();//Open Blank array for number of data
foreach($json as $k => $v):
$num [] = $v; //number of data
endforeach;
$row= count($num);//Put number of data in $row
for($i=0; $i<$row; $i++){
//instead of putting the value in the statement, store them in variable
$com_name = $json[$i]['com_name'];
$city = $json[$i]['city'];
$com_address = $json[$i]['com_address'];
//Put the other variable like this and put them in insert statement
$stmt = mysqli_prepare($con, "INSERT INTO company_details VALUES (?, ?,?)");
mysqli_stmt_bind_param($stmt, 'sss', $com_name, $city, $com_address);
}
This is just a simple working solution( working demo with real database). I don't have no time for typing all the fields. For the second and third loop, there is no fax number, so if the data field default value cannot have null value, there will be some problem and your statement will not work properly and likely fails. I hope this will help.
I'm using BlueImp jQuery File Upload with database integration, adapting the script found here.
I changed a bit the handle_file_upload() method like this:
$sql = 'INSERT INTO '.$this->options['db_table'].' (`path`, `type`, `tab`, `item`) VALUES (?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'ssii',
$path = $this->options['upload_url'] . $file->name,
$file->type,
$file->tab,
$file->item
);
but, on the line $path = $this->options['upload_url'] . $file->name, I have a Strict Standards: Only variables should be passed by reference error
Well, I have no idea how to change this...
I tried to look at other answers, but they don't fit into my case: please any help? Thanks
Since it is passed by reference the variable needs to exist before binding
$path = $this->options['upload_url'] . $file->name;
$sql = 'INSERT INTO '.$this->options['db_table'].' (`path`, `type`, `tab`, `item`) VALUES (?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'ssii',
$path,
$file->type,
$file->tab,
$file->item
);
This should work...
$sql = 'INSERT INTO '.$this->options['db_table'].' (`path`, `type`, `tab`, `item`) VALUES (?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$p = $this->options['upload_url'] . $file->name;
$query->bind_param(
'ssii',
$p,
$file->type,
$file->tab,
$file->item
);
You were setting $path's value in the parameter binding. So it wouldn't return anything.
Read more here: Strict Standards: Only variables should be passed by reference
$sql = 'INSERT INTO '.$this->options['db_table'].' (`path`, `type`, `tab`, `item`) VALUES (?, ?, ?, ?)';
$query = $this->db->prepare($sql);
$upload_url = $this->options['upload_url'] . $file->name;
$query->bind_param(
'ssii',
$path = $upload_url,
$file->type,
$file->tab,
$file->item
);
I would like to have data inserted in one table, and data updated in another through prepared statements in mysqli. Trying the following only executes the INSERT command:
EDITED:
if($stmt=$mysqli->prepare("SELECT bids_id, bid, fruit_volume FROM basket ORDER BY bid DESC")) {
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($bids_id, $bid, $fruit_volume);
while($stmt->fetch()) {
$stack = array($bids_id, $bid, $fruit_volume);
array_push($all_fruits, $stack);
}
$stmt->free_result();
}
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();
bind_param passes by reference not by value,so you need to have those values in variables before they can be referenced
$a=800;
$b=1;
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii',$a, $b);
$stmt3->execute();
}
}
Try this instead
foreach ($all_fruits as $fruits) {
if ($_POST["offer"] == $fruits[1] && $volume < $fruits[2]) {
$stmt2 = $mysqli->prepare("INSERT INTO oranges (username, price, volume, date) VALUES (?, ?, ?, ?)");
$stmt2->bind_param('sdis', $user, $price, $volume, $today);
$stmt2->execute();
$stmt3 = $mysqli->prepare("UPDATE basket SET fruit_volume = ? WHERE bids_id = ?");
$stmt3->bind_param('ii', 800, 1);
$stmt3->execute();
}
}
$mysqli->close();
My PHP form I just changed to use PDO. The only thing I can tell is the execute is not working. Am I supposed to pass something with it?
$db = new PDO('mysql:host=localhost;dbname=x;charset=utf8', 'x', 'x');
if ( !$db )
{
die('Could not connect: ' . mysql_error());
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$mail = $_POST['mail'];
$stmt = $db->prepare("SELECT * FROM ucm_signup WHERE email =? ");
$stmt->bindValue(1, $mail, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()== 0) {
//if there are no duplicates...insert
$sql = $db->prepare("INSERT INTO ucm_signup (company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress)
VALUES (:company, :address1, :address2, :city, :province, :zip, :fname, :lname, :mail, :phone, :session, :iama, :buyfrom, :group1, :ipaddress)");
$sql->bindParam(":company", $_POST['company'],PDO::PARAM_STR);
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":city", $_POST['city'],PDO::PARAM_STR);
$sql->bindParam(":province", $_POST['province'],PDO::PARAM_STR);
$sql->bindParam(":zip", $_POST['zip'],PDO::PARAM_STR);
$sql->bindParam(":fname", $_POST['fname'],PDO::PARAM_STR);
$sql->bindParam(":lname", $_POST['lname'],PDO::PARAM_STR);
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR);
$sql->bindParam(":phone", $_POST['phone'],PDO::PARAM_STR);
$sql->bindParam(":session", $_POST['session'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":buyfrom", $_POST['buyfrom'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":group1", $_POST['group1'],PDO::PARAM_STR);
$sql->bindParam(":ipaddress", $_POST['ipaddress'],PDO::PARAM_STR);
$sql->execute();
}
My database table has no records. Thank you
You are missing some placeholder in your bind parameters, check them carefully
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":address2", $_POST['city'],PDO::PARAM_STR);
//address2 was missed, probably error is column doesn't match values
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR); //supposed to be mail
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR); //supposed to be iama
You might want to check for pdo errors, here an example taken from manual
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
With this attribute correctly added pdo will notify you if any error occur
PHP users are so PHP users.
First they're laboring on a WALL of code, consists of constantly repeating nearly hundred variables.
Then they get totally lost.
While everything can be done with short and concise code, writing each field name only ONCE
$allowed = array('company', 'address1', 'address2', 'city', 'province',
'zip', 'fname', 'lname', 'email', 'phone', 'session',
'iama', 'buyfrom', 'group1', 'ipaddress');
$_POST['ipaddress'] = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO ucm_signup SET ".pdoSet($allowed, $values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
where pdoSet() helper function can be stored elsewhere and reused for the every insert or update query
function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`".str_replace("`","``",$field)."`". "=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}