I have this script:
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
$stmt->execute();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
And it is basically inserting around 157K (157 THOUSAND) rows of data. And the data is quite big as well! You can't check the file_get_contents URL out because the port is open only to localhost.
What is the quickest way to insert all this data? It has been running for almost 24 hours now and done 65K. I did try and use transactions but that didn't work well. It gave my 502 Bad Gateway and therefore I lost a lot of time on the script because it rolled back after adding 3 thousand rows (which was however quite quick!)
Also it is possible that the script may at some point fail and leave some of the varchar fields as null hence I have made it so that they end up as an empty string so that there aren't any mySql errors (I got those exceptions thrown when using transactions)
This is the code I used with the transaction stuff. I'm pretty new to prepared statements. I converted this code from standard queries to prepared today and then tried transactions.
<?php
ini_set('max_execution_time', 0);
ini_set('display_errors','1');
ini_set('default_charset','utf-8');
include("includes/mysqli.php");
$con->set_charset("utf8");
$sql = "INSERT INTO clans(id, clanid, name, badge, status, playercount, score, requiredtrophies, warswon, warslost, warstied, location,warfrequency, exp, level, description, playerjson, lastupdate)
VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, now())";
$stmt = $con->prepare($sql); //prepare update statement
$stmt->bind_param('ssisiiiiiissiiss',$clanid,$name,$badge,$status,$playercount,$score,$requiredtrophies,$warswon,$warslost,$warstied,$location,$warfrequency,$exp,$level,$description,$playerarray);
$stmts = $con->prepare("SELECT * FROM activeclans WHERE id > 137439657919 ORDER BY id ASC"); //Prepare select statement
$stmts->execute(); //execute select statement
$result = $stmts->get_result(); //get select statement results
try{
$con->autocommit(FALSE);
while ($row = $result->fetch_assoc()) {
$clanid = $row['id'];
$clanurl = "http://185.112.249.77:9999/Api/clan?clan=$clanid";
$jsondata = file_get_contents($clanurl);
$data = json_decode($jsondata,true);
if($data['name'] != null){
$name = $data['name'];
}else{
$name = "";
}
$badge = $data['badge'];
if($data['status'] != null){
$status = $data['status'];
}else{
$status = "";
}
$playercount = $data['playerCount'];
$score = $data['score'];
$requiredtrophies = $data['requiredTrophies'];
$warswon = $data['warsWon'];
$warslost = $data['warsLost'];
$warstied = $data['warsTied'];
if($data['clanLocation'] != null){
$location = $data['clanLocation'];
}else{
$location = "";
}
if($data['warFrequency'] != null){
$warfrequency = $data['warFrequency'];
}else{
$warfrequency = "";
}
$exp = $data['exp'];
$level = $data['level'];
$description = $data['description'];
$playerarray = json_encode($data['players']);
/* Execute update statement */
if(!$stmt->execute()){
throw new Exception("Cannot insert record. Reason :".$stmt->error);
}
}
$con->commit();
}catch (Exception $e) {
echo 'Transaction failed: ' . $e->getMessage();
$con->rollback();
}
echo $stmt->affected_rows;
$stmt->close();
$stmts->close();
$con->close();
?>
Thanks :)
$sql="
INSERT INTO
ue_game_alliance_rank_rights
(
rank
, `right`
)
VALUES
";
$insertQuery = array();
$insertData = array();
foreach ($rights_status['add'] AS $row ) {
$insertQuery[] = '(?,?)';
$insertData[] = $rank;
$insertData[] = $row['id'];
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $this->db->prepare($sql);
$stmt->execute($insertData);
}
}
That's an example of the basic technique, you would need to swap the functions for their equivalent mysqli_* functions. For each field having data inserted into it, you need:
$insertData[] = $row['id'];
$row needs to match whatever you've used in your foreach loop and ['id'] needs to be whatever the name of the field is that you're inserting into.
$insertQuery[] = '(?,?)';
You need as many placeholders as fields that you'll be inserting into.
Overall it creates a bulk insert, so you need to have the data to be inserted in an array. Given the amount of data that you're inserting, use transactions, you'll probably need to experiment to see how many rows you can bulk insert at a time before the server complains
Related
I cannot fint the error nor could find ideas from the internet.
The database has key, userIP, and date.
the code segment is:
$last = $conn->query("SELECT LAST_INSERT_ID();");
if (strcmp($last, "<empty string>") == 0) {
$index = 0;
} else {
$index = $last + 1;
}
$stmt = $conn->prepare("INSERT INTO Users (key, userIP, date) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $key, $ip, $date);
$key = $index;
$ip = $_SERVER['REMOTE_ADDR'];
$date = date('Y-m-d H:i:s');
The idea is that I save the last "key" and add 1 to it. Tho it doesn't seems to work if the db is empty. I was looking over it for hours so I have ran out on ideas.
You need to fetch the results of the query.
$result = $conn->query("SELECT LAST_INSERT_ID();");
$row = $result->fetch_row();
$last = $row[0];
if ($last == "") {
$index = 0;
} else {
$index = $last + 1;
}
But you don't need to perform a query for this, there's a built-in function for it:
$last = $conn->insert_id;
Another problem is that key is a reserved word, so you need to quote it with backticks.
$stmt = $conn->prepare("INSERT INTO Users (`key`, userIP, date) VALUES (?, ?, ?)");
So it's probably a really stupid/basic question, but i have this simple PHP function (which works) and inserts data into a PostgreSQL DB.
My issue is when it encounters specific data;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = $csvfile[$x]['email'];
$name = $csvfile[$x]['name'];
$surname = $csvfile[$x]['surname'];
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
$x++;
}
}
And while this works, it falls over with a surname such as:
O'hare
And obviously this occurs because then the PHP code comes out as:
...VALUES ('john#example.com', 'John', 'O'hare')";
but im not sure of how i should be structuring the PHP to allow for this.
Try this:
function insertData($pg, $csvfile) {
$nbr = count(file($csvfile));
for($i=0; $i<$nbr; $i++) {
$email = pg_escape_string( $csvfile[$i]['email'] );
$name = pg_escape_string( $csvfile[$i]['name'] );
$surname = pg_escape_string( $csvfile[$i]['surname'] );
$query = "INSERT INTO users (email, name, surname) VALUES ('$email', '$name', '$surname')";
$result = pg_query($pg, $query);
if (!$result) {
echo "Error while executing the query: " . $query;
exit;
}
}
}
You need to escape the string parameters. And it is much better if you can use PDO extension, because prepared statements can take care of escaping for you and also helps with preventing SQL injection and some other security concerns.
function insertData(PDO $dbh, $csvfile) {
$x = 0;
foreach ($csvfile as $data)
{
$query = "INSERT INTO users (email, name, surname) VALUES (?, ?, ?)";
$params = [
$csvfile[$x]['email'],
$csvfile[$x]['name'],
$csvfile[$x]['surname']
];
$statement = $pdo->prepare($query);
$statement->execute();
$x++;
}
}
PDO::prepare
PDOStatement::execute
Solution using prepared query
function insertData($dbname, $tbname, $csvfile)
{
$result = [];
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=$dbname");
// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'INSERT INTO $1 (email, name, surname) VALUES ($2, $3, $4)');
// Execute the prepared query. Note that it is not necessary to escape
foreach ($csvfile as $data)
{
$email = $data['email'];
$name = $data['name'];
$surname = $data['surname'];
$query = "";
$result[] = pg_execute($dbconn, "my_query", array($tbname, $email, $name, $surname));
}
if (in_array(false, $result) )
return false;
else
return true;
}
$dbname = "your dbname";
$tbname = "name of table";
$csvFile = [];
if (insertData($dbname, $tbname, $csvFile))
echo "Data inserted";
else
echo "Data not inserted";
So i took note of the suggestions from #Karsten Koop and #TOH19, and came up with this code which is working;
function insertData($pg, $csvfile)
{
$x = 0;
foreach ($csvfile as $data)
{
$email = pg_escape_string($csvfile[$x]['email']);
$name = pg_escape_string($csvfile[$x]['name']);
$surname = pg_escape_string($csvfile[$x]['surname']);
$query = "INSERT INTO users (email, name, surname) VALUES ('".$email."', '".$name."', '".$surname."')";
$result = pg_query($pg, $query);
$x++;
}
}
I have a form which contain two table. Each of the table able to add table row. which mean when submit a form using isset $_POST by using "for" right? the things that i concern about is how to submit a single form which contain two table (both of them have function add table row) in single database table. Both of table contain slightly different attribute but in the same database table. i was searching this for a week and didnt found solution yet. I only able to submit a form which contain one table (which have add table row). How about if there is two table but insert into same database table?
if(isset($_POST['submitbtn'])){
//others
$merchant = $_POST['merchant'];
$remark = $_POST['remark'];
$docno = $_POST['docno'];
$category = $_POST['category'];
$claim_amount = $_POST['claim_amount'];
//airfare
$airline = $_POST["airline"];
$origin = $_POST["origin"];
$destination = $_POST["destination"];
$descript = $_POST["desc"];
$docno_air = $_POST["docno_air"];
$category_air = $_POST["category_air"];
$claim_amount_fare = $_POST["claim_amount_fare"];
$email = $ColUser['Email'];
$euser = $_SESSION['UserId'];
$reportName = $_POST['reportname'];
$start_date = date("Y-m-d");
$status="open";
$purpose = $_POST["purpose"];
//get approval
$getapproval = "SELECT * FROM `approve_by` WHERE `user_id` = '".$_SESSION['UserId']."'";
$approvalget = mysqli_query($mysqli,$getapproval);
$appid = mysqli_fetch_assoc($approvalget);
$app1 = $appid['approval_1'];
$app2 = $appid['approval_2'];
$app3 = $appid['approval_3'];
//generate travel id
$travelprefix= "SELECT * FROM `prefix` WHERE `description` = 'Travel'";
$result_travel = mysqli_query($mysqli, $travelprefix);
$travel_info = mysqli_fetch_assoc($result_travel);
$travel_pre = $travel_info['prefix'];
$travel_old_num = $travel_info['running_number'] + 1;
$travel_new = sprintf("%05d", $travel_old_num);
$travel_date_append = date('mY');
$travel_number = $travel_pre."-".$travel_date_append."-".$travel_new;
//generate report id
$reportprefix= "SELECT * FROM `prefix` WHERE `description` = 'REPORT'";
$result_report = mysqli_query($mysqli, $reportprefix);
$report_info = mysqli_fetch_assoc($result_report);
$report_pre = $report_info['prefix'];
$report_old_num = $report_info['running_number'] + 1;
$report_new = sprintf("%05d", $report_old_num);
$report_date_append = date('mY');
$report_number = $report_pre."-".$report_date_append."-".$report_new;
if (!empty($_POST['airline']))
{
for ($i = 0; $i < count($_POST["airline"]); $i++){
$airline = $_POST["airline"][$i];
$origin = $_POST["origin"][$i];
$destination = $_POST["destination"][$i];
$descript = $_POST["desc"][$i];
$docno_air = $_POST["docno_air"][$i];
$category_air = $_POST["category_air"][$i];
$claim_amount_fare = $_POST["claim_amount_fare"][$i];
//$upload_dir = 'upload';
//$targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR;
$targetPaths="upload/";
$filefare = $targetPaths.rand(1000,100000)."-".$_FILES['bill_image_air']['name'][$i];
$file_loc = $_FILES['bill_image_air']['tmp_name'][$i];
$file_basename = substr($filefare, 0, strripos($filefare, '.'));
//$flink='http://localhost/new_exp/'.$file;
move_uploaded_file($file_loc,$filefare);
$mrecordprefix= "SELECT * FROM `prefix` WHERE `description` = 'Category'";
$mresult_record = mysqli_query($mysqli, $mrecordprefix);
$mrecord_info = mysqli_fetch_assoc($mresult_record);
$mrecord_pre = $mrecord_info['prefix'];
$mrecord_old_num = $mrecord_info['running_number'] + 1;
$mrecord_new = sprintf("%05d", $mrecord_old_num);
$mrecord_date_append = date('mY');
$mrecord_number = $mrecord_pre."-".$mrecord_date_append."-".$mrecord_new;
$save_running_records = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Category'";
$save_running_report = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Report'";
$save_running_travel = "UPDATE `prefix` SET `running_number`=? WHERE `description` = 'Travel'";
$save_new_record = "INSERT INTO `report`(`reportname`, `report_ref`, `UserId`, `CategoryId`, `travel_record`, `remark`, `claim_amount`, `bill_image`, `bill_image_type`, `docno`, `origin`, `airline`, `destination`, `email_from`, `approval_1`, `approval_2`, `approval_3`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$save_count = "INSERT INTO `categorycount`(`CategoryId`, `amount`, `userid`, `categoryno`) VALUES (?, ?, ?, ?)";
$stmt6 = $mysqli->prepare($save_running_records);
$stmt4 = $mysqli->prepare($save_running_report);
$stmt2 = $mysqli->prepare($save_running_travel);
$stmt5 = $mysqli->prepare($save_new_record);
$stmt7 = $mysqli->prepare($save_count);
$stmt6->bind_param('s', $mrecord_old_num);
$stmt4->bind_param('s', $report_old_num);
$stmt2->bind_param('s', $travel_old_num);
$stmt5->bind_param('ssiisssbssssssiii', $reportName, $report_number, $euser, $category_air, $travel_number, $descript, $claim_amount_fare, $filefare, $filefare, $docno_air, $origin, $airline, $destination, $email, $app1, $app2, $app3);
$stmt7->bind_param('isis', $category_air, $claim_amount_fare, $euser, $mrecord_number);
if ($stmt5->execute() == false){
echo 'Fifth query failed: ' . $mysqli->error;
} else {
if ($stmt2->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt4->execute() == false){
echo 'gl B query failed: ' . $mysqli->error;
} else {
if ($stmt7->execute() == false) {
echo 'gl B query failed: ' . $mysqli->error;
} else {
if($stmt6->execute() == false){
echo 'gl C query failed: ' . $mysqli->error;
}
$stmt6->close();
}
$stmt7->close();
}
$stmt4->close();
}
$stmt2->close();
}
$stmt5->close();
}
}
airfare table image
others expenses table image
My current problem is now how to handle if table in other expense tab is empty? because when i try to submit form and fill in all the input except for the others expense tab table which i let it empty. when i submit the form, the empty row in other expense tab table is insert in database table as well..
Hi I'm trying to update my tbl_jadwal, it said success, but database is not updated, anybody can please help me finding where the problem is ? Thankyou
<?php
if (isset($_GET['id'])) {
$ID = $_GET['id'];
} else {
$ID = "";
}
// create array variable to store category data
$category_data = array();
$sql_query = "SELECT Category_ID, Category_name
FROM tbl_category
ORDER BY Category_ID ASC";
$stmt_category = $connect->stmt_init();
if ($stmt_category->prepare($sql_query)) {
// Execute query
$stmt_category->execute();
// store result
$stmt_category->store_result();
$stmt_category->bind_result($category_data['Category_ID'],
$category_data['Category_name']
);
}
$sql_query = "SELECT Menu_image FROM tbl_jadwal WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('s', $ID);
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->bind_result($previous_menu_image);
$stmt->fetch();
$stmt->close();
}
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Execute query
$stmt->execute();
// store result
$stmt->store_result();
$stmt->fetch();
$stmt->close();
}
if (isset($_POST['btnEdit'])) {
$nama_lokasi = $_POST['nama_lokasi'];
$category_ID = $_POST['category_ID'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$description = $_POST['description'];
// get image info
$menu_image = $_FILES['menu_image']['name'];
$image_error = $_FILES['menu_image']['error'];
$image_type = $_FILES['menu_image']['type'];
// create array variable to handle error
$error = array();
// updating all data
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?, Latitude = ?, Longitude = ?, Phone = ?, Email = ?, Menu_image = ?, Description = ?
WHERE Menu_ID = ?";
$upload_image = 'upload/images/' . $menu_image;
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('ssssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
} else {
updating all data except image file
$sql_query = "UPDATE tbl_jadwal
SET Nama_Lokasi = ? , Category_ID = ?,
Longitude = ?, Latitude = ?, Phone = ?, Email = ?, Description = ?
WHERE Menu_ID = ?";
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query)) {
// Bind your variables to replace the ?s
$stmt->bind_param('sssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$description,
$ID);
// Execute query
$stmt->execute();
// store result
$update_result = $stmt->store_result();
$stmt->close();
}
}
check update result
if ($update_result) {
$error['update_data'] = " <span class='label label-primary'>Success update</span>";
} else {
$error['update_data'] = " <span class='label label-danger'>failed update</span>";
}
This my database structure
replace bind_param() with bindParam(':data', $data);
or try $stmt->execute(array(':data' => $data))
Hi Just write the simple query firstly and add EXPLAIN before it.
For example:
EXPLAIN update table set name='test' where id=1;
This statement will show all the possible error. In this way you will be able to resolve the problem.
I am using Opencart v2.2.0 and I am having problem with my php script. The line in question is:
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
The whole function including the line above is as follows:
function restoreBackup()
{
global $mysqli;
$i = 0;
$getpic = "SELECT * FROM oc_product_backup LIMIT 0, 100000";
$backup = $mysqli->query($getpic);
$mysqli->autocommit(FALSE);
$updateproduct_sql = "UPDATE oc_product SET image = ?, ean = ?, model = ?, status = ?, price_sync = ?, modified_by = ?, date_modified = ? WHERE product_id= ?";
$updatedescription_sql = "UPDATE oc_product_description SET name = ?, description = ?, meta_description = ?, meta_keyword = ?, tag = ?, modified_by = ? WHERE product_id = ? AND language_id = ?";
$stmt = $mysqli->prepare($updateproduct_sql);
$stmt->bind_param('sssiiiss', $image, $ean, $model, $status, $price_sync, $modified_by, $date_modified, $product_id);
$stmt2 = $mysqli->prepare($updatedescription_sql);
$stmt2->bind_param('sssssisi', $name, $description, $meta_description, $meta_keyword, $tag, $modified_by, $product_id, $language_id);
while($row = $backup->fetch_array(MYSQLI_ASSOC))
{
//$name = removeslashes($row['name']);
$name = $row['name'];
//$description = removeslashes($row['description']);
$description = $row['description'];
$meta_description = $row['meta_description'];
$meta_keyword = $row['meta_keyword'];
$tag = $row['tag'];
$product_id = $row['product_id'];
$modified_by = $row['modified_by'];
$language_id = $row['language_id'];
if($row['language_id'] == 4)
{
$image = $row['image'];
$ean = $row['ean'];
$name = $row['name'];
$model = $row['model'];
$status = $row['status'];
$price_sync = $row['price_sync'];
$date_modified = $row['date_modified'];
if(!$stmt->execute())
return false;
}
if(!$stmt2->execute())
return false;
$i++;
if(($i % 500) === 0) $mysqli->commit();
}
$mysqli->commit();
$backup->close();
return true;
}
function removeslashes($string)
{
$string=implode("",explode("\\",$string));
return stripslashes(trim($string));
}
The error I get is
Fatal error: Call to a member function bind_param() on boolean in
Any suggestions, please? I do not see what am I doing wrong. Thank you all in advance.
The prepare() method can return false and you should check for that. As for why it returns false, perhaps the table name or column names (in SELECT, UPDATE or WHERE clause) are not correct?
Also, consider use of something like $query->error_list to examine errors that occurred parsing the SQL. (I'll occasionally echo the actual SQL statement strings and paste into phpMyAdmin to test, too, but there's definitely something failing there.)