Php Bulk insert - php

I have the code with php using bulk insert.,I run the code and there is no error., The Problem there is no OUTPUT with this code and blank page/screen appear .. All I want to do is to have the Output with the page and with the database using this code ..
<?php
$dbh = odbc_connect(
"DRIVER={SQL Server Native Client 10.0};Server=.;Database=ECPNWEB",
"sa", "ECPAY");
if (($handle = fopen("c:\\tblmcwd.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 4096, "|")) !== FALSE) {
if (count($data) == 10) {
$sql = "INSERT INTO [dbo].[tblMCWD] (
[ID],
[ConsumerCode],
[ConsumerName],
[AccountStatus],
[AccountNumber],
[DueDate],
[CurrentBill],
[PreviousBill],
[TotalDiscount],
[TotalGrossAmountDue]
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(1, $data[0]);
$stmt->bindValue(2, $data[1]);
$stmt->bindValue(3, $data[2]);
$stmt->bindValue(4, $data[3]);
$stmt->bindValue(5, $data[4]);
$stmt->bindValue(6, $data[5]);
$stmt->bindValue(7, $data[6]);
$stmt->bindValue(8, $data[7]);
$stmt->bindValue(9, $data[8]);
$stmt->bindValue(10, $data[9]);
$stmt->execute();
}
}
fclose($handle);
}
?>

Try this:
....
$sql = "INSERT INTO [dbo].[tblMCWD] (
[ID],
[ConsumerCode],
[ConsumerName],
[AccountStatus],
[AccountNumber],
[DueDate],
[CurrentBill],
[PreviousBill],
[TotalDiscount],
[TotalGrossAmountDue]
) VALUES (
:ID, :ConsumerCode, :ConsumerName, :AccountStatus, :AccountNumber, :DueDate, :CurrentBill, :PreviousBill, TotalDiscount, TotalGrossAmountDue
)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':ID', $data[0]);
$stmt->bindParam(':ConsumerCode', $data[1],PDO::PARAM_STR);
$stmt->bindParam(':ConsumerName', $data[2],PDO::PARAM_STR);
$stmt->bindParam(':AccountStatus', $data[3],PDO::PARAM_STR);
$stmt->bindParam(':AccountNumber', $data[4],PDO::PARAM_STR);
$stmt->bindParam(':DuaDate' , $data[5],PDO::PARAM_STR);
$stmt->bindParam(':CurrentBill', $data[6],PDO::PARAM_STR);
$stmt->bindParam(':PreviousBill', $data[7],PDO::PARAM_STR);
$stmt->bindParam(':TotalDiscount', $data[8],PDO::PARAM_STR);
$stmt->bindParam(':TotalGrossAmountDue', $data[9],PDO::PARAM_STR);
$stmt->execute();
if(!$stmt){ // Check if the query executed succesfull, if not, print the data...
$printedString = "ID: %1$s ConsumerCode: %2$s ConsumerName: %3$s"; // and so on....
$printedString = sprintf($printedString , $data[0],$data[1],$data[2]); // and so on...
} else{
echo "Everything executed succesfully!<br />";
}
More info can you find here: Link
And here: Link 2
And here: Link 3
Use PDO::PARAM_STR for strings and PDO::PARAM_INT for an integer, and give it an try

Related

multiple json data into mysql database table not inserting

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.

Mysqli INSERT command followed by an UPDATE

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();

Mysqli Prepared Statement Troubleshooting

I'm stumped, I recently had this working in plain Mysqli statements, but was told to avoid injection to write it using prepared statements. The truncate is the only thing that seems to work. Any advice?
$con=mysqli_connect(localhost,"username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = 'twitch'
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json?channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert->bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();$deletetable = $con->prepare('TRUNCATE TABLE twitch_streams');
$deletetable->execute();
$deletetable->close();
$result = $con->prepare("SELECT field_value
FROM xf_user_field_value
WHERE field_id = twitch
AND field_value != ''");
$result->bind_result($twitchfield);
while($result->fetch())
{
printf("%s\n", $twitchfield);
$username[] = $twitchfield;
$data = json_decode(file_get_contents('http://api.justin.tv/api/stream/l ist.json? channel=' . $username[0]));
$viewer[] = $data[0]->channel_count;
$insert = $con->prepare("INSERT INTO twitch_streams (twitchuser, viewercount)
VALUES (?, ?)");
$insert = bind_param('si', $twitchuser, $viewercount);
$twitchuser = $username[0];
$viewercount = $viewer[0];
$insert->execute();
echo $twitchuser;
echo $viewercount;
$insert->close();
}
$result->close();
mysqli_close($con);
There is no function bind_param(), it is a method of mysqli_stmt
You use it like so:
$insert->bind_param()
Check here for more information on mysqli_stmt

import .CSV file with PHP using PDO

I'm having a problem importing .CSV data into a SQL database. I'm trying to use PDO in my PHP file to accomplish this and I can't seem to figure this out.
if (isset($_FILES['uploadedfile'])) {
// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited, account_id
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?
)');
$data = fgetcsv($handle,1000,",","'");
$query_ip->execute($data);
$count = $query_ip->rowCount();
fclose($handle);
} catch(PDOException $e) {
die($e->getMessage());
}
echo 'Projects imported ' . $count . ' rows were affected';
} else {
echo 'Could not import projects';
}
Now this works, kind of. It imports the data but as you may have guessed this is only inserting the first row of the .CSV file, which by the way is the column headers. So I need to skip the first row and loop through the rest of this .CSV file.
Obviously throwing me some code would solve this, but more than that I would like an explanation of how to do this properly with PHP Data Objects (PDO). All the examples I've come across either have huge flaws or don't use PDO. Any and all help is welcomed and appreciated.
The comments helped me come up with this answer. I used the following code
if (isset($_FILES['uploadedfile'])) {
// get the csv file and open it up
$file = $_FILES['uploadedfile']['tmp_name'];
$handle = fopen($file, "r");
try {
// prepare for insertion
$query_ip = $db->prepare('
INSERT INTO projects (
id, project_name, contact, pm, apm,
est_start, est_end, trips, tasks, perc_complete,
bcwp, actual, cpi, bcws, bac,
comments, status, project_revenue, profit_margin, pm_perc,
audited
) VALUES (
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?
)
');
// unset the first line like this
fgets($handle);
// created loop here
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$query_ip->execute($data);
}
fclose($handle);
} catch(PDOException $e) {
die($e->getMessage());
}
echo 'Projects imported';
} else {
echo 'Could not import projects';
}
I hope this helps future readers properly import their .CSV files using PDO. It should be noted this should not be used on a live server/site. This code has 0 protection against potentially harmful uploads.
error_reporting(E_ALL);
ini_set('display_errors', 1);
/* Database connections */
$_host = 'localhost';
$_name = 'root';
$_password = 'root';
$_database = 'TEST';
/* ========= Variables =========== */
/**
* Defines the name of the table where data is to be inserted
*/
$table = 'terms';
/**
* Defines the name of the csv file which contains the data
*/
$file = 'terms.csv';
/* =========== PDO ================= */
try {
$link = new PDO('mysql:dbname=' . $_database . ';host=' . $_host . ';charset=utf8', $_name, $_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$link->exec("set names utf8");
} catch (PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
/* ========= Load file content in an array ========== */
$rows = array_map('str_getcsv', file($file));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
$csv[] = array_combine($header, $row);
}
/* ========= Insert Script ========== */
foreach ($csv as $i => $row) {
insert($row, $table);
}
function insert($row, $table) {
global $link;
$sqlStr = "INSERT INTO $table SET ";
$data = array();
foreach ($row as $key => $value) {
$sqlStr .= $key . ' = :' . $key . ', ';
$data[':' . $key] = $value;
}
$sql = rtrim($sqlStr, ', ');
$query = $link->prepare($sql);
$query->execute($data);
}
echo "Done inserting data in $table table";

adding error msg to prepared statements

I'm trying to convert mysql_query over to prepared statements, but it's failing silently and I'm not sure where I'm going wrong. Here's my proc.php page for a form:
$db = new PDO('mysql:host=XXX;dbname=XXX;charset=utf8', 'XXX', 'XXX');
if ($_POST['submit']) {
$type = $_POST['type'];
$auth1_lname = trim($_POST['auth1_lname']);
$auth1_fname = trim($_POST['auth1_fname']);
$today = date("Y-m-d");
$stmt = $db->prepare("INSERT INTO table_base ( type , publ_date , auth1_lname , auth1_fname )
VALUES (:type, :today, :auth1_lname , :auth1_fname) ");
$stmt->bindParam(':type', $type);
$stmt->bindParam(':today', $today);
$stmt->bindParam(':auth1_lname', $auth1_lname);
$stmt->bindParam(':auth1_fname', $auth1_fname);
$stmt->execute();
$bid = $db->lastInsertId();
$subj_area = $_POST['subj_area'];
$subject = 'subj_area';
$subjs = '';
$stmt = $db->prepare("INSERT INTO table_meta (bid, key, value) VALUES (:bid, :key, :value)");
$stmt->bindParam(':bid', $bid);
$stmt->bindParam(':key', $subject);
$stmt->bindParam(':value', $subjs, PDO::PARAM_STR);
foreach($subj_area as $subjs) {
$stmt->execute();
}
$geo_area = $_POST['geo_area'];
$geograph = 'geo_area';
$geos = '';
$stmt = $db->prepare("INSERT INTO table_meta (bid, key, value) VALUES (:bid, :key, :value)");
$stmt->bindParam(':bid', $bid);
$stmt->bindParam(':key', $geograph);
$stmt->bindParam(':value', $geos, PDO::PARAM_STR);
foreach($geo_area as $geos) {
$stmt->execute();
}
}
I'm not sure I'm even doing this right.
I see comments elsewhere on SO that your PHP must be this tall to use PDO, but php.net's page on PDO doesn't list PHP requirements. Am I failing b/c my PHP5 host doesn't have the right drivers?
Is there a way to add a die(mysql_error()) so at least it wouldn't be a silent failure?

Categories