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 am trying to enter data from html into MSSQL database using php. I am unable to insert record in 2 different tables and unable to insert multiple records to a table, I have the code below
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$company = $_POST["company"];
$contact = (int)$_POST["contact"];
$worktitle = $_POST["worktitle"];
$industry = $_POST["industry"];
$V101 = $_POST["part2q1"];
$V102 = $_POST["part2q2"];
$V103 = $_POST["part2q3"];
$V104 = $_POST["part2q4"];
$V105 = $_POST["part2q5"];
$V106 = $_POST["part2q6"];
$V107 = $_POST["part3q1"];
$V108 = $_POST["part3q2"];
$V109 = $_POST["part3q3"];
$V110 = $_POST["part3q4"];
$V111 = $_POST["part3q5"];
$V112 = $_POST["part3q6"];
$V113 = $_POST["part4q1"];
$V114 = $_POST["part4q2"];
$V115 = $_POST["part4q3"];
$V116 = $_POST["part4q4"];
$V117 = $_POST["part4q5"];
$V118 = $_POST["part4q6"];
$V119 = $_POST["part5q1"];
$V120 = $_POST["part5q2"];
$V121 = $_POST["part5q3"];
$V122 = $_POST["part5q4"];
$V123 = $_POST["part5q5"];
$V124 = $_POST["part5q6"];
$V125 = $_POST["part6q1"];
$V126 = $_POST["part6q2"];
$V127 = $_POST["part6q3"];
$V128 = $_POST["part6q4"];
$V129 = $_POST["part6q5"];
$V130 = $_POST["part6q6"];
$V131 = $_POST["part7q1"];
$V132 = $_POST["part7q2"];
$V133 = $_POST["part7q3"];
$V134 = $_POST["part7q4"];
$V135 = $_POST["part7q5"];
$V136 = $_POST["part7q6"];
$V137 = $_POST["part7q7"];
$V138 = $_POST["part7q8"];
$V139 = $_POST["part8q1"];
$V140 = $_POST["part8q2"];
$V141 = $_POST["part8q3"];
$V142 = $_POST["part8q4"];
$V143 = $_POST["part8q5"];
$V144 = $_POST["part8q6"];
$currenttime = date("Ymd h:m:sa");
$server = "***";
$connOptions = array("Database"=>"**", "UID"=>"**", "PWD"=>"**!");
$conn = sqlsrv_connect($server, $connOptions);
if($conn){
$query="INSERT INTO dbo.profile (
name,
email,
company,
telephone,
worktitle,
industry,
createdate
)
VALUES (?, ?, ?, ?, ?, ?,getdate())";
$params = array(
$name,
$email,
$company,
$contact,
$worktitle,
$industry,
$currenttime
);
if(sqlsrv_query($conn, $query, $params)){
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
Im trying to insert records to another table like this continuing from the previous line:
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V101,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V102,$currenttime);
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Value,
CreatedOn
)
VALUES ('2', ?, ?, ?, ?, ?,getdate())";
$params=array($V103,$currenttime);
. . . . .
if(sqlsrv_query($conn, $query1, $params))
{
echo "<h4>Thank you</h4><p>You have completed the survey and your answers have been received.</p>";
} else {
echo "<p>We're sorry but there has been and error receiving your answers.</p>";
}
} else {
echo "<p>We're sorry but there has been and error receiving your answers. </p>";
}
?>
I have been trying this, insert works for first table but not the second table, can anyone help please
The following worked for me to enter multiple records to second table. Thanks to Miken32
if($conn){
$query1="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params1=array(2,101,$V101,$currenttime);
if(sqlsrv_query($conn, $query1, $params1))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
if($conn){
$query2="INSERT INTO dbo.SurveyResponse (
profileid,
Qid,
Value,
CreatedOn
)
VALUES (?, ?, ?,getdate())";
$params2=array(2,102,$V102,$currenttime);
if(sqlsrv_query($conn, $query2, $params2))
{
echo "";
}
else { echo"<p>We're sorry but there has been and error receiving your answers.</p>" ; }
}
I tried to make the update statement to be safety againts sql injection but its give me this erro Fatal error: Call to a member function bind_param() on a non-object on line 39
$pid = $_POST['pid'];
$pagetitle = $_POST['pagetitle'];
$linklabel = $_POST['linklabel'];
$keyword = $_POST['keyword'];
$descriere = $_POST['descriere'];
$data = $_POST['data'];
$pagebody = $_POST['pagebody'];
// Filter Function -------------------------------------------------------------------
function filterFunction ($var) {
$var = nl2br(htmlspecialchars($var));
$var = str_replace("/", "\\\\", $var);
$var = preg_replace("~/~", "\\\\", $var);
return $var;
}
$pagetitle = filterFunction($pagetitle);
$linklabel = filterFunction($linklabel);
$keyword = filterFunction($keyword);
$descriere = filterFunction($descriere);
$data = filterFunction($data);
$pagebody = filterFunction($pagebody);
// End Filter Function --------------------------------------------------------------
include_once "../conx.php";
// Add the updated info into the database table
$stmt = $con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
$stmt->execute();
$stmt->close();
line 39 is $stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
it is necessary to make this or i can revert to how it was before
$query = mysqli_query($con, "UPDATE pages SET pagetitle='$pagetitle', linklabel='$linklabel', pagebody='$pagebody', lastmodified='now()' WHERE id='$pid'") or die (mysqli_error($con));
Didn't this produce an error?
$con->prepare("UPDATE pages SET (pagetitle, linklabel, keywords, description, pagebody, lastmodified) VALUES (?, ?, ?, ?, ?, ?) WHERE id = ?");
this should be
$con->prepare("UPDATE pages SET pagetitle=?, linklabel=?, keywords=?, description=?, pagebody=?, lastmodified=? WHERE id = ?");
Refer: http://dev.mysql.com/doc/refman/5.7/en/update.html
now you can proceed to bind parameters
$stmt->bind_param("sssssss", $pagetitle, $linklabel, $keyword, $descriere, $pagebody, $data, $pid);
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.
So I'm working on this project here and I"m trying to do a prepared statement so I can handle any odd objects like slashes and what not as the raw data comes through. However, when I go to execute the statement it provides the same error over and over again:
SQLSTATE: 07002
code: 0
message: [Microsoft][SQL Server Native Client 11.0]COUNT field incorrect or syntax error
it says that my field count is incorrect, but I checked all the variables and made sure everything that was supposed to be there, is. So I'm just a little confused I guess. Also to note this is my first time working with the sqlsrv prepared statements, so any help would be awesome!
Here is my code below:
<?php
$serverName = "localhost";
$connectionInfo = array( "Database"=>"devel", "UID"=>"root", "PWD"=>"");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$error_message = "";
$xml = trim(file_get_contents('/file.xml'));
$xml = new SimpleXMLElement($xml);
$truck_number;
$date_time;
$speed;
$heading;
$gps_quality;
$latitude;
$longitude;
$location;
$fix_type;
$ignition;
$gps_odometer;
$gps_rolling_odometer;
$performx_odometer;
$performx_fuel;
$performx_speed;
$performx_idle;
$packet_id;
sqlsrv_begin_transaction($conn);
$error_count = 0;
$q = "INSERT INTO eagle_devel.dbo.people_net (truck_number, date_time, speed, heading, gps_quality, latitude, longitude, location, fix_type, ignition, gps_odometer, gps_rolling_odometer,
performx_odometer, performx_fuel, performx_speed, performx_idle, packet_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = sqlsrv_prepare($conn, $q, array(&$truck_number, &$date_time, &$speed, &$heading, &$gps_quality, &$latitude, &$longitude, &$location, &$fix_type, &$ignition, &$gps_odometer, &$gps_rolling_odometer, &$performx_odometer, &$performx_fuel, &$performx_speed, &$performx_idle, &$packet_id));
foreach($xml->loc_history as $loc_history){
$truck_number = $loc_history->truck_number;
$date_time = $loc_history->datetime;
$speed = $loc_history->speed;
$heading = $loc_history->heading;
$gps_quality = $loc_history->gps_quality;
$latitude = $loc_history->latitude;
$longitude = $loc_history->longitude;
$location = $loc_history->location;
$fix_type = $loc_history->fix_type;
$ignition = $loc_history->ignition;
$gps_odometer = $loc_history->gps_odometer;
$gps_rolling_odometer = $loc_history->gps_rolling_odometer;
$performx_odometer = $loc_history->performx_odometer;
$performx_fuel = $loc_history->performx_fuel;
$performx_speed = $loc_history->performx_speed;
$performx_idle = $loc_history->performx_idle;
$packet_id = $xml->packet_id;
if(sqlsrv_execute($stmt) === false){
$error_count++;
if(($errors = sqlsrv_errors()) != null){
foreach($errors as $error){
$error_message .= "SQLSTATE: ".$error['SQLSTATE']."<br>";
$error_message .= "code: ".$error['code']."<br>";
$error_message .= "message: ".$error['message']."<br><br>";
}
}
}
}
if($error_count)
sqlsrv_rollback($conn);
else
sqlsrv_commit($conn);
print $error_message;
?>
UPDATE : I was told to try and initialize the variables before hand so I did and I get this.
SQLSTATE: IMSSP
code: -16
message: An invalid PHP type for parameter 1 was specified.
I have no idea what this means so I'm researching.