Mysql converting multiple insert statements into one - php

I have a script to upoad an excel file and insert data from the xlsx file to a mysql table . It is like this
<?php
require_once('Connections/met.php');
$file = './uploads/windrose_data.xlsx';
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$msg="File upload successful";
$db=mysql_select_db($database_met,$met);
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
$inputFileName = $file;
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$date = trim($allDataInSheet[$i]["A"]);
$time = trim($allDataInSheet[$i]["B"]);
$dir = trim($allDataInSheet[$i]["C"]);
$spd = trim($allDataInSheet[$i]["D"]);
$insertTable= mysql_query("insert into wr_copy (date,time,dir,spd) values('$date', '$time',$dir,$spd)") or die(mysql_error());
$msg=$i-1." records inserted into the table";
}
echo $msg;
} else {
echo "Upload Failed";
}
?>
here for each row in excel one insert statement is executed., then I am sending a response using the iteration variable as the number of records inserted. There are two issues, one, I want to use a single insert statement which can be used for inserting all the rows in excel. second issue is using iterating variable values as no. of records can be a problem because, the query may not execute if there is any error in data. Can anybody suggest a work around for this?

For creating the one statement:
$statement = 'insert into wr_copy (date,time,dir,spd) values';
$values = [];
for($i=2;$i<=$arrayCount;$i++){
$date = trim($allDataInSheet[$i]["A"]);
$time = trim($allDataInSheet[$i]["B"]);
$dir = trim($allDataInSheet[$i]["C"]);
$spd = trim($allDataInSheet[$i]["D"]);
$values[] = "('$date', '$time',$dir,$spd)";
}
$statement .= implode(',',$values);
To get the real numbers of records that are inserted (i copied the example from here and change it):
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare($statement)) {
/* execute statement */
$stmt->execute();
printf("rows inserted: %d\n", $stmt->affected_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>

Related

How can i get all the values in the query?

<?php
$mysqli = new mysqli("localhost", "root", "", "titan3d");
if (mysqli_connect_error()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sdate = "";
$stime = "";
if(isset($_POST['sdate']))
{
$sdate = $_POST["sdate"];
}
if(isset($_POST['stime']))
{
$stime = $_POST["stime"];
}
$statement = $mysqli->prepare("SELECT bookedseat FROM bookings WHERE sdate = ? AND stime = ?");{
$statement->bind_param("si", $sdate, $stime);
if (!$statement->execute()) {
trigger_error('Error executing MySQL query: ' . $statement->error);
}
$statement->bind_result($book);
$statement->fetch();
printf($book);
//header('Location: http://localhost/My%20Project/seats.html');
$statement->close();
}
$mysqli->close();
?>
This is my php file made to get the data from a form and make a query and then display the results.
When executed,the php works perfectly.
But it only displays the first value in the query.
Why is it?
How can I display all the values in my query?
You need to use $stmt->fetch() in a while loop, you can then iterate over each the returned row.
while ($stmt->fetch()) {
// $book will have the value of bookedseat for the current row
}

CSV uploading without browse button

I want to upload the contents of a CSV while one PHP page is running. I don't want any browse button to upload the CSV. Whenever the page is running the page should find the CSV which the path is already defined in the PHP page and contents should be inserted into the table. Now I am getting error related with fopen.
Here is my code
<?php
//database connection details
$connect = mysql_connect('localhost', 'root', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid = mysql_select_db('test', $connect);
// path where your CSV file is located
define('CSV_PATH', 'D:/xamp/htdocs/test/');
// Name of your CSV file
$csv_file = CSV_PATH . "test.csv";
echo $csv_file;
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c = 0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
$col4 = $col[3];
$col5 = $col[4];
$col6 = $col[5];
// SQL Query to insert data into DataBase
$query = "INSERT INTO testcsv(Line,Part No,Make,Model,Year,Part Type) VALUES('" . $col1 . "','" . $col2 . "','" . $col3 . "','" . $col4 . "','" . $col5 . "','" . $col6 . "')";
$s = mysql_query($query, $connect);
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
I am getting this error
Warning: fopen(D:/xamp/htdocs/test/test.csv): failed to open stream: No such file or directory in D:\xamp\htdocs\test\test.php on line 22
File data successfully imported to database!!
Can anyone help me?
I'm not sure why you are getting that particular error - one might assume that the file does not exist or that the directory is not readable but you are using the now deprecated mysql_ functions and directly embedding variables in the sql - thus making it vulnerable to sql injection. However, as this looks to be only a test that is probably not an issue.
The preferred method for this type of thing would be to use either mysqli or PDO in conjunction with prepared statements - below is an example of how you might implement that - I tested this with different data and database details and it seemed to work fine.
define('CSV_PATH','D:/xamp/htdocs/test/');
$filepath = CSV_PATH . "test.csv";
/* database connection details */
$host = 'localhost';
$uname = 'xxx';
$pwd = 'xxx';
$db = 'xxx';
/* create db connection */
$con = new mysqli( $host, $uname, $pwd, $db );
/* construct required sql statement */
$sql='insert into `testcsv` (`Line`,`Part No`,`Make`,`Model`,`Year`,`Part Type`) values (?,?,?,?,?,?)';
/* create prepared statement */
$stmt=$con->prepare( $sql );
if( !$stmt ){
echo 'error preparing sql statement!';
$con->close();
} else {
/* bind the columns to variables which will be populated later */
/* use "i" for integer and "s" for string values */
$stmt->bind_param( 'ssssss', $line,$part,$make,$model,$year,$type );
/* access csv file */
$file=new SplFileObject( $filepath );
/* Process each row of the csv file */
while( !$file->eof() ) {
/* read the line into a variable */
$data=$file->fgetcsv();
if( !empty( $data ) ){
/* assign a variable to each field value for this row */
list( $line,$part,$make,$model,$year,$type )=$data;
/* execute statement with the now defined variables */
$stmt->execute();
}
}
/* tidy up */
$stmt->close();
$con->close();
echo 'database updated with new records from csv';
}

update picture into database table using php

I have an address table and one of the fields is an image blob. When I update a record through $POST and include an image, everything works. However if no image is included in $POST, I want to reuse the image that is already stored in the record. This is were im having problems. when I run the code below it does not update the image file. here's my code.
function UpdateRecordfromPost()
{
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$FirstName = test_input($_POST['fname']);
$LastName = test_input($_POST['lname']);
$Address = test_input($_POST['address']);
$Town = test_input($_POST['town']);
$Postcode = test_input($_POST['pcode']);
$Phone = test_input($_POST['phone']);
$Email = test_input($_POST['email']);
$ID = ($_POST['idname']);
}
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $mysqli->connect_error);
}
$image = GetimagefromPost(); //this function returns a image and seems to work
if ($image == "")
{
$image = Saveimaqgefile($ID);
}
$query = "UPDATE addressbook SET firstname='$FirstName',lastname='$LastName',street='$Address',town='$Town',PostCode='$Postcode',phone='$Phone',email='$Email',Photo='$image' WHERE id='$ID'";
if ($result = $mysqli->query($query))
{
echo "Updated record successfully";
}
else
{
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$mysqli->close();
}
function Saveimaqgefile($file_id) {
$mysqli = new mysqli( $GLOBALS['servername'], $GLOBALS['username'], $GLOBALS['password'], $GLOBALS['dbname']);
if ($mysqli->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql= "SELECT * from ".$GLOBALS['dbname']. " WHERE id=".$file_id;
$result = $mysqli->query($sql);
if ($result->num_rows > 0)
{
$row=mysqli_fetch_array($result);
}
else { $row = "";}
$mysqli->close();
return base64_encode($row['Photo']);
}
This is my first question, sorry if i've done something wrong
You'd need conditional logic.
if (image was uploaded) {
mysqli_query('... update record with new image ...;);
} else {
mysqli_query('... update record WITHOUT image data ...');
}
For most other types of (small) data, you could do it in a single query, e.g.
UPDATE ... SET field=IF($newdata = '', field, $newdata)
but your image blob is likely to be HUGE, and you don't want to repeat it twice in the same query string.

How to import excel data into MySQL database?

I have used the following code to read the data of exceltodb.xlsx file and import it into the table city of database world. The library to read the file is PHPExcel which is very common library.The code I found is as follows but the code is executing but the row is not added into the database.
<?php
include 'PHPExcel-develop/Classes/PHPExcel/IOFactory.php';
$inputFileName = 'exceltodb.xlsx';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load('exceltodb.xlsx');
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
mysql_connect('localhost','root','');
mysql_select_db('world');
mysql_query('insert into city("city","id","stateid","countryid") values("$rowData")');
}
?>
This code segment will upload your xml data sheet in to a particular location in the server:
<?php
$uploadedStatus = 0;
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
}
$storagename = "discussdesk.xlsx";
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename);
$uploadedStatus = 1;
}
} else {
echo "No file selected <br />";
}
}
?>
This will upload the data taken from xml to the database:
<?php
/************************ YOUR DATABASE CONNECTION START HERE ****************************/
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$databasetable = "YOUR_TABLE";
/************************ YOUR DATABASE CONNECTION END HERE ****************************/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
$inputFileName = 'discussdesk.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$userName = trim($allDataInSheet[$i]["A"]);
$userMobile = trim($allDataInSheet[$i]["B"]);
$query = "SELECT name FROM YOUR_TABLE WHERE name = '".$userName."' and email = '".$userMobile."'";
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$existName = $recResult["name"];
if($existName=="") {
$insertTable= mysql_query("insert into YOUR_TABLE (name, email) values('".$userName."', '".$userMobile."');");

how to concatenate sql queries

i am trying to concatenate sql queries and run later after loop. how is that possible? this is my vision:
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
sql = sql . " insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
and save into db:
for($j=0;$j<sqlarray.length;$j++){
$sql_done = mysql_query($sqlarray[$j]);
}
i didnot try anything yet, because the database is big and i am afraid of destroying something important with my code..
thanks a lot
Use mysqli and bindings
see http://www.php.net/manual/en/mysqli.prepare.php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->close();
Binding will avoid a lot of security issue, no one should use something else then binding ever.
Even better put everything in a transaction and in case of error your database remains unchanged.
see: http://www.php.net/manual/en/mysqli.commit.php for more info
and here is a proposal with commit or rollback
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if (mysqli_connect_errno()) {
throw new Exception("Unable to connect");
}else{
try{
$mysqli->autocommit(FALSE);
// define your query
$query = "INSERT INTO tablename (column1,column2) VALUES (:col1,:col2)";
if ($stmt = $mysqli->prepare($query)) {
// loop of insert
for($i=0;$i<10;$i++){
$stmt->bind_param("col1", $i);
$stmt->bind_param("col2", 'test'.$i);
$stmt->execute();
}
$stmt->close();
}else{
throw new Exception("unable to prepare query");
}
$mysqli->commit();
}catch(Exception $e){
$mysqli->rollback();
}
$mysqli->close();
}
I did not try it but we should be near a good (best practice?) solution.
I hope this could help you.
For insert query you can write code like below:
$sql .= " insert into table (`item`) values ";
for($i=1;$i<=10;$i++){
$item_.$i = "value_".$i;
$sql = $sql . " ('$item_'.$i.''),";
}
mysqli_query( substr($sql ,0,-1) );
The above will concatenate all the insert data in a single string and execute at once.
I hope you were looking for this
$query = "insert into table_name values";
for($i=0;$i<4;$i++) {
$data1 = "test_".$i;
$data2 = "new_".$i;
$query .= "('','$data1','$data2'),";
}
$query = substr($query,0,-1);
echo $query;
Let me know
try below code
$sql="":
for($i=1;$i<=10;$i++)
{
$item_.$i = "value_".$i;
$sql.=" insert into table (`item`) values ('$item_'.$i.'')";
// this should be but an array
}
mysql_query($sql);

Categories