SQL Server Prepared Statement saying invalid column count - php

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.

Related

PHP & SQL Server: how to insert data into 2 tables and insert multiple rows

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>" ; }
}

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.

Inserting multidiamenstional array into mysql with pdo [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I've a multidimensional array to insert into mysql table. Trying to add datetime time along with other elements in that array.
but everytime i get this error. :
Notice: Undefined offset: 10 in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php on line 47
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'att_status' cannot be null' in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php:60 Stack trace: #0 C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php(60): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\Auto-attendance\main\proccess_attendance.php on line 60
I don't get where is the prob.
<?php
require_once("db_const.php");
if (!$_SERVER['REQUEST_METHOD']=='POST'
|| !$_POST['submit']=='save'
|| empty($_POST['subject_name'])
|| empty($_POST['subject_code'])
|| empty($_POST['department_name'])
|| empty($_POST['department_short_name'])
|| empty($_POST['teacher_name'])
|| empty($_POST['date'])
|| empty($_POST['time'])
|| empty($_POST['student'])
|| empty($_POST['stroll'])
|| empty($_POST['status'])
) {
header('Location: ../student_attendance.php?page=take-attendance');
} else {
## connect mysql server
/** $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} :
{$mysqli->connect_error}</p>";
exit();
}**/
## query database
# prepare data for insertion 538 072 662 2716
$subject_name = $_POST['subject_name'];
$subject_code = $_POST['subject_code'];
$department_name = $_POST['department_name'];
$department_short_name = $_POST['department_short_name'];
$teacher_name = $_POST['teacher_name'];
$date = $_POST['date'];
$time = $_POST['time'];
$student = $_POST['student'];
$student_roll = $_POST['stroll'];
$status = $_POST['status'];
$date=date_create_from_format("j-M-Y", $date);
$date= date_format($date,"Y-m-d");
$timestamp = date('Y-m-d H:i:s');
foreach($student as $k=>$v){
$st[] = array($subject_name, $subject_code, $department_name,
$department_short_name, $teacher_name, $date, $time, $timestamp, $v,
$student_roll[$k], $status[$k]); }
$db = new PDO('mysql:host=localhost;dbname=auto_attendance', 'root',
'');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $db->prepare(
'INSERT INTO student_attendance (subject_name , subject_code,
department_name, department_short_name,
teacher_name, date, time, timestamp, student_name, student_roll,
att_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach($st as $values) {
$result = $insert->execute($values);
}
if($result == true) {
echo "<script>alert('Record successfuly
Saved.');window.location.href='../student_attendance.php?page=take-
attendance';</script>";
}
else {
echo "<script>alert('Record couldnt be
Saved.');window.location.href='../student_attendance.php?page=take-
attendance';</script>";
}
}
?>
Well your code is a bit of a mess, so I cleaned as much as I could:
1. I changed your if statement so that it is a bit more readable also I remove the else part, since you redirect if something isn't set.
2. Also put an exit(); after each header() call. To make sure the script execution is stopped.
3. Also I wrapped your database stuff into a try and catch block to catch PDOExceptions
4. I also changed the assignment of the execute() call, since you want to check if every execution was successful and not only the last one
<?php
require_once("db_const.php");
function checkPostIndex(array $indexes = [""]) {
if(empty($indexes)) return FALSE;
return array_reduce($indexes, function($result, $v){
return $result && !empty($_POST[$v]);
}, TRUE);
}
$indexes = ["subject_name", "subject_code", "department_name", "department_short_name", "teacher_name", "date", "time", "student", "stroll", "status"];
if($_SERVER["REQUEST_METHOD"] !== "POST" || $_POST['submit'] !== "save" || checkPostIndex($indexes)) {
header("Location: ../student_attendance.php?page=take-attendance");
exit();
}
$subject_name = $_POST['subject_name'];
$subject_code = $_POST['subject_code'];
$department_name = $_POST['department_name'];
$department_short_name = $_POST['department_short_name'];
$teacher_name = $_POST['teacher_name'];
$date = $_POST['date'];
$time = $_POST['time'];
$student = $_POST['student'];
$student_roll = $_POST['stroll'];
$status = $_POST['status'];
$date = DateTime::createFromFormat("j-M-Y", $date)->format("Y-m-d");
$timestamp = date("Y-m-d H:i:s");
foreach($student as $k => $v) {
$tmpOne = (!empty($student_roll[$k])?$student_roll[$k]:"");
$tmpTwo = (!empty($status[$k])?$status[$k]:"");
$st[] = [$subject_name, $subject_code, $department_name, $department_short_name, $teacher_name, $date, $time, $timestamp, $v, $tmpOne, $tmpTwo];
}
try {
$db = new PDO("mysql:host=localhost;dbname=auto_attendance", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $db->prepare('INSERT INTO student_attendance
(subject_name , subject_code, department_name, department_short_name, teacher_name, date, time, timestamp, student_name, student_roll, att_status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
foreach($st as $values) {
$result[] = $insert->execute($values);
}
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
<script>alert('Record <?php echo (!in_array("FALSE", $result, true)?"successfuly":"couldnt be") ?> Saved.');window.location.href='../student_attendance.php?page=take-attendance';</script>
Side Notes:
Add error reporting at the top of your file(s) to get useful error messages:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
(Turn it on only while testing, never in production!)
The problem is with the value being passed in to $_POST['status']; If you track down what is being passed in to this variable you will find it is the problem!

php mysql prepared statements issue

I'm starting with mysql prepared statements and I can't advance due to an error that I don't understand. Here's my function to update de db:
public function updateUserData($user_label,$user_alliance, $score, $rank, $timestamp, $user_id, $db_object){
$sql='UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ?';
$label = $user_label;
$alliance = $user_alliance;
$points = $score;
$position = $rank;
$modified = $timestamp;
$user_id_q = $user_id;
$stmt = $db_object->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db_object->error, E_USER_ERROR);
}
$stmt->bind_param('ssiiii',$label,$alliance,$points,$position,$modified,$user_id_q);
/* Execute statement */
$stmt->execute();
echo $stmt->affected_rows;
$stmt->close();
}
Here's how I use it:
//Get user Data
$user = new user();
$page_clasif = $user->getPagClasif($ch,$url_clasif);
$user_label = $user->findPlayerName($page_clasif);
$user_alliance = $user->findAllianceName($page_clasif);
$rank = $user->findRank($page_clasif);
$score = $user->findScore($page_clasif);
$user_id = $user->findPlayerId($page_clasif);
$version = $user->findVersion($page_clasif);
$user_universe = $user->findUniverse($page_clasif);
//Get install date as timestamp
$core = new core();
$timestamp = $core->dateAsTimestamp();
//Update User
$user->updateUserData($user_label,$user_alliance,$score,$rank,$timestamp,$user_id,$conn);
Here's the error:
PHP Fatal error: Wrong SQL: UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ? Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE user_id = ?'
Any ideas?
Thanks in advance.
You have a superfluous comma before the WHERE keyword:
$sql='UPDATE users SET label = ?, alliance = ?, points = ?, position = ?, modified = ?, WHERE user_id = ?';
// remove this comma --^

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";

Categories