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 (?, ?, ?)");
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..
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
I have a save.php page that is being called using Ajax, it contains the following elements:
$q1 = $_POST["q1"];
$q2 = $_POST["q2"];
$q3 = $_POST["q3"];
$q4 = $_POST["q4"];
$q5 = $_POST["q5"];
$proc = mysqli_prepare($link, "INSERT INTO tresults
(respondent_id, ip, browser, company, q1, q2, q3, q4, q5)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);");
mysqli_stmt_bind_param($proc, "issiiiii",
$respondent_id, $ip, $browser, $company,
$q1, $q2, $q3, $q4, $q5);
At the moment, the save.php page is manually coded but I am sure there must be a way of using variable variables to automate this page to a degree, especially when the number of fields exceeds 100 that I am saving to the database.
I am, however, having trouble getting my head around using variable variables and could use some guidance.
I am have, to no avail, tried the following:
for ($i = 1; $i <= 5; $i++) {
echo '$q.$i = $_POST["q".$i];';
}
and also
for ($i = 1; $i <= 5; $i++) {
$q.$i = $_POST["q".$i];
}
Any and all advice welcomed.
Thanks.
You can use:
${'q'.$i} = $_POST['q'.$i];
Also:
for ($i = 1; $i <= 5; $i++) {
echo '$q.$i = $_POST["q".$i];';
}
should be:
for ($i = 1; $i <= 5; $i++) {
echo "$q.$i = $_POST['q'.$i];";
// ^ ^
}
otherwise variables won't be interpolated within the string.
Wrap them in {} like
for ($i = 1; $i <= 5; $i++) {
${'q'.$i}=$_POST['q'.$i];
}
Please got through this once for reference http://www.php.net/manual/en/language.variables.variable.php
I have a text file, who's value i have put into arrays,
this is the php code:
<?php
$homepage = file_get_contents('hourlydump.txt');
$x = explode('|', $homepage);
$desc = array();
$cat = array();
$link = array();
$m = 1;
$n = 2;
$p = 3;
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$p = $p + 4;
if ($x[$p])
$link[] = $x[$p];
}
echo "<pre>";
print_r($desc);
print_r($cat);
print_r($link);
?>
output is like:
Array
(
[0] => Kamal Heer - Facebook Official Video 720p Dual Audio [Hindi + Punjabi]76 mb by rANA.mkv
[1] => 50 HD Game Wallpapers Pack- 1
)
Array
(
[0] => Movies
[1] => Other
)
Array
(
[0] => http://kickass.to/kamal-heer-facebook-official-video-720p-dual-audio-hindi-punjabi-76-mb-by-rana-mkv-t7613070.html
[1] => http://kickass.to/50-hd-game-wallpapers-pack-1-t7613071.html
)
//
//
//
anyone please help me i dont know how to insert the values of these three arrays $desc, $cat and $link
into mysql table, columns named description, category, link
i know simple insert queries but dont how to deal with these arrays.
I will give you an example of how basic database connection is made and the insert is completed, this is for illustrative purpose only. You should reorganize this code inside a class so that every insert statement doesn't create a PDO object but re-use the object created before.
function insertItem($desc, $cat, $link) {
$dbh = new PDO("mysql:host=host;dbname=db", $user, $pass);
$sql = "INSERT INTO table (description, category, link) VALUES (:desc, :cat, :link)";
$sth = $dbh->prepare($sql);
$sth->bindValue(":desc", $desc);
$sth->bindValue(":cat", $cat);
$sth->bindValue(":link", $link);
$sth->execute();
}
You can use a for statement.
for($x =0, $num = count($desc); $x < $num; $x++){
// build you query
$sql = "INSERT into your_table (description, category, link) values ".
"(".$db->quote($desc[$x]).",".$db->quote($cat[$x]).",".
$db->quote($link[$x].")";
$db->query($sql);
}
Of course you will have to use the sanitation/quoting methods appropriate for your chosen database api.
Here is a simple sample to read your file as is from the website you retrieve it as well as inserting it to the database sanitizing the data:
<?php
// fill with your data
$db_host = 'localhost';
$db_user = '';
$db_pass = '';
$db_name = '';
$db_table = 'myTable';
$file = "hourlydump.txt.gz";
if($filehandle = gzopen($file, "r"))
{
$content = gzread($filehandle, filesize($file));
gzclose($file);
}
else
die('Could not read the file: ' . $file);
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if($con->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
if (!$insert = $con->prepare($sql))
die('Query failed: (' . $con->errno . ') ' . $con->error);
foreach (explode("\n", $content) as $line)
{
list($md5hash,$desc,$cat,$link,$torrent) = explode("|", $line);
if (!$insert->bind_param('sss',$desc,$cat,$link))
echo 'Binding parameters failed: (', $insert->errno, ') ', $insert->error;
if (!$insert->execute())
echo 'Insert Error ', $insert->error;
}
$insert->close();
$con->close();
NOTE: you may want to check if the file was loaded with success, if the fields from the explode exist or not to prevent further problems but in general this should work just fine.
Also you may want to change the $sql to reflect your MySQL table aswell as the $db_table at the top.
UPDATE: to insert all values change this:
$sql = "INSERT INTO $db_table (description, category, link) VALUES (?, ?, ?)";
To:
$sql = "INSERT INTO $db_table (md5, description, category, link, torrent) VALUES (?, ?, ?, ? ,?)";
And this:
if (!$insert->bind_param('sss',$desc,$cat,$link))
To:
if (!$insert->bind_param('sssss',$md5hash,$desc,$cat,$link,$torrent))
Note above the s for each item you need a s you have 5 items so 5 s's the S means string, D double, I integer, B blob you can read more at about it here.
Also note the $sql for each item we will use on the bind_param we have a ?.
Try this. I am assuming that only these much of values are there for insertion
for($i = 0;$i<2;$++) {
mysqli_query("INSER INTO tablename values(description,category,link) VALUES('$desc[$i]'
,'$cat[$i]','$link[$i]')");
}
You can build your query while you're doing you calculations:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$query .= "('".$x[$m];
$n = $n + 4;
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]) $query .= "','".$x[$p]."'),";
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
You can also build the arrays along with the query if you need to:
$query = "INSERT INTO `table` (`description`, `category`, `link`) VALUES ";
for ($i = 1; $i <= count($x) / 4; $i++) {
$m = $m + 4;
$desc[] = $x[$m];
$query .= "('".$x[$m];
$n = $n + 4;
$cat[] = $x[$n];
$query .= "','".$x[$n];
$p = $p + 4;
if ($x[$p]){
$link[] = $x[$n];
$query .= "','".$x[$p]."'),";
} else {
$link[] = $x[$n];
else $query .= "',NULL),";
}
$query = substr($query, 0, -1);//get rid of last comma
mysqli_query($query);
make the array to a string
$description = json_encode($desc);
$category = json_encode($cat);
$link = json_encode($link);
then insert these values to database
At the time of fetching
Use json_decode to get the array again from the string