MySQL insert not working, syntax seems okay with phpMyAdmin - php

I am working with the following php syntax:
$sqlgo = "INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('$invoice_id','$product','$description','$price','$qty','$discount',NOW(),'$update_id')";
$dbconnect->query($sqlgo);
When PHP performed the code above, nothing being inserted into the db but when I echo $sqlgo and performed it in phpMyAdmin, everything seems to be fine. Here's the echo sample of the sql:
INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('118','Sport Socks','','20.00','1','0',NOW(),'1')
Did I miss anything? Hold on .. lemme paste the whole for loop just in case:
$item_maintain = array();
$test = 0;
$sqlgo = "";
for($i=0;$i<count($invoice_product);$i++) {
if(!empty($invoice_product[$i])) {
$product = addslashes($invoice_product[$i]);
$description = addslashes($invoice_product_desc[$i]);
$qty = trim($invoice_product_qty[$i]);
$price = trim($invoice_product_price[$i]);
if (!$invoice_product_discount[$i]) {
$discount = 0;
} else {
$discount = trim($invoice_product_discount[$i]);
}
if (!empty($item_current[$i])) {
$dbconnect->query("UPDATE invoice_qtydisc SET name='$product', description='$description', price='$price', qty='$qty', discount='$discount', updated=NOW(), updated_by='$update_id' WHERE id='$item_current[$i]'");
array_push($item_maintain, $item_current[$i]);
} else {
$sqlgo = "INSERT INTO invoice_qtydisc (`invoice_id`,`name`,`description`,`price`,`qty`,`discount`,`created`,`created_by`) VALUES ('$invoice_id','$product','$description','$price','$qty','$discount',NOW(),'$update_id')";
$dbconnect->query($sqlgo);
$dbconnect->query("INSERT INTO pin_board (title,message) VALUES ('title here','message here')");
$test++;
}
}
}
The 2nd insert line into table "pin_board" worked flawlessly though.

Related

Is there a way to update 12000+ rows from txt file in less then 2mins?

I need to update a table with more then 12000 row using php Codeigniter and a txt file.. reading the file and the foreach loop are fine but when updating line by line it takes like 30 mins, I guess the problem is I'm searching by name because I have no id in the txt file...
Here is my code:
controller:
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
$update = $this->model_products->update3s($pieces);
}
}
fclose($fn);
Model:
public function update3s($product) {
if ($product) {
$product[2] = trim(str_replace("'","''",$product[2]));
$product[1] = trim($product[1]);
$product[6] = trim($product[6]);
$product[3] = trim($product[3]);
$sql = "UPDATE products set qty = $product[3], price_vente = $product[6] where (name = '$product[2]')";
echo $sql.'<br>';
$update = $query = $this->db->query($sql);
return $update;
}
return false;
}
You can use transaction and add index for column name in database table.
$fn = fopen($this->upload->data('full_path'),"r");
$update = true;
$updatedCount = 0;
while(! feof($fn) && $update) {
$pieces = explode("|", fgets($fn));
if(sizeof($pieces) == 9 && is_numeric(trim($pieces[1]))) {
if ($updatedCount == 0) {
$databaseInstance->beginTransaction();
}
$update = $this->model_products->update3s($pieces);
++$updatedCount;
if ($updatedCount > 500) { //in one transaction update 500 rows
$databaseInstance->commit();
$updatedCount = 0;
}
}
}
if ($updatedCount > 0) { // if we have not commited transaction
$databaseInstance->commit();
}
fclose($fn);
Some tips
Add index to field name
Use prepared statements
Disable the MySQL forgeign key check Read more
writing sql function can do that even in much lesser time .
using feature like :
REPLACE()
cursors
SPLIT_STRING(custom)
in a mysql user defined function
CREATE FUNCTION update3s(hole_file_content LONGTEXT) RETURNS Boolean
BEGIN
-----Your implementation(same logic in sql ) ------
END
then coll it just by if it is CI 3
$this->db->call_function('update3s', file_get_contents($this->upload->data('full_path')));
else
$this->db->query("select update3s(".file_get_contents($this->upload->data('full_path')).")");

Prevent insert query with php

I have a php which will include my datas inside my database.
But in my page I have a div which can be replicated, so I send this informations into an array (imploded with a "#!#" to avoid any kind of wrong explode when I insert it on my database).
My problem is that if the user doesn't insert anything on the first div content fields I shall not do the insert, and it still does.
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Try checking the first item in the foreach:
if ($_GET['action_ent'] != "#!##!##!#")
{
$myInputs = $_GET['action_ent'];
foreach ($myInputs as $eachInput)
{
if(empty($eachInput)) {
echo 'NOTHING';
break;
}
$valores = $eachInput;
print_r($valores);
$dummy = explode('#!#', $valores);
$acao = $dummy[0];
$resp_acao = $dummy[1];
$inic_plan_acao = $dummy[2];
$fim_plan_acao = $dummy[3];
$inicio_acc = explode("/", $inic_plan_acao);
$fim_acc = explode("/", $fim_plan_acao);
$inicio_action = $inicio_acc[2]."-".$inicio_acc[1]."-".$inicio_acc[0];
$fim_action = $fim_acc[2]."-".$fim_acc[1]."-".$fim_acc[0];
$result2 = mysql_query("INSERT INTO `demv3`.`entraves_action` (`action_id`, `ent_id`, `resp_ent`, `data_fim`,`action_desc`,`action_resp`,`action_comeco`,`action_fim`) VALUES ('0', '$ent_id', '$resp_ent', '$data_fim', '$acao', '$resp_acao', '$inicio_action', '$fim_action')");
}
}
else
{
echo "NOTHING";
}
Just be aware that if any other input besides the first one is empty it will break the loop. In order to avoid major changes in your logic you can resolve this with a counter or a boolean flag:
if(empty($eachInput) && $counter == 0) {
echo 'NOTHING';
break;
}

MySQL Update with field being a concatenated string

function updateUser($userData, $statsID) {
$fields = '';
$config = 0;
while(list($key,$val)= each($userData)) {
if($config++ != 0){
$fields .= ' , ';
}
$col = $key;
$val = $val;
$fields .= "$col='$val'";
}
//echo $fields;
global $dbhandle;
$query = mysqli_query($dbhandle, "UPDATE data SET $fields WHERE statsID = '$statsID'");
echo var_export($query); <--returns NULL
In this code, I pass in an array as noted below:
$sendData = array('name'=>$name,'race'=>$race,'rank'=>$rank,'highestRank'=>$highestRank,'commander'=>$commander,'atkSld'=>$atkSld,'atkMerc'=>$atkMerc,'defSld'=>$defSld,'defMerc'=>$defMerc,'untSld'=>$untSld,'untMerc'=>$untMerc,'spies'=>$spies,'sentries'=>$sentries,'morale'=>$morale,'tff'=>$tff,'strike'=>$strike,'strikeRank'=>$strikeRank,'defense'=>$defense,'defenseRank'=>$defenseRank,'spy'=>$spy, 'spyRank'=>$spyRank, 'sentry'=>$sentry, 'sentryRank'=>$sentryRank, 'fort'=>$fort,'siege'=>$siege,'economy'=>$economy,'tech'=>$tech,'conscription'=>$conscription,'gold'=>$gold,'tbg'=>$tbg,'gameTurns'=>$gameTurns,'covertLvl'=>$covertLvl);
I have confirmed all the data is set and correct. The statsID passes in correctly and when I echo field, it gives me exactly what is required to fulfill my query and in the correct format (key='value' , key ='value' , key ='value etc)
EDIT: Problem solved, I have updated my code to reflect the solution. For some reason I had to call global $dbhandle prior to the query string. If someone could tell me why that would be great!

How to check a value of a variable and call different function

I have the following variables in my cart.php file:
<?php $readyTotal = $qty*price ?>;
Now I want to do is that if the $readyTotal > $1000 then call a file which is adding an item into the customer's cart.
($slq= msyql_query("INSERT into `table`.....value.....");
and if the value of $radyTotal < $1000;
dont add any extra item or if it has been added just remove it by calling the removal file.
($sql =mysql_query("DELETE from `table` where .......");
Please note that how to do this I want to call/include the files in my cart.php file. but i am unable to do this. is there any other way to do it or by using ajax/jquery which check every the value of $readyTotal every time when it changes.
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND `signature`='".getSignature()."'");
}
When I try the above function individual file it works fine, but when i use both in it does not woks please.... what is wrong with this...
<?php
include_once("customfunctionfile.php");
$object = new quiz;
$readyTotal = $qty*price ;
if($readyTotal > 1000){
$object->ad();
}else{
$object->removeMe();
}
?>;
customfunctionfile.php
class quiz{
function ad(){
$signature =getSignature();
$item = 21;
$type = 100;
$type= 0;
$sql2 = mysql_query("Select * From `temp` where `item`='$item' AND `price`= 0 AND
`signature`='$signature' AND `type`=0 AND `toppings`=0 " );
$count= mysql_num_rows($sql2);
if($count ==0){
$sql = mysql_query("INSERT INTO `temp`
(`item`,`price`,`signature`,`type`,`toppings`, `isCoupon`)
VALUES
('$item','$type','$signature','0','0', '1')");
}
}
function removeMe(){
mysql_query("DELETE FROM `temp` WHERE `item`=21 AND
`signature`='".getSignature()."'");
}
}
You can achieve this something like this using functions without including file.
<?php
$readyTotal = $qty*price;
if($readyTotal > 1000) //considering amount in $
{
addItemToCart($cartDetails) // call function to add item into the cart
}
else {
removeItemFromCart($cartDetails) //call function to remove item from cart
}
?>
Define functions addItemToCart and removeItemFromCart to fire your queries.

Retrieving value from database in CodeIgniter is not working

In my Codeigniter project ,table value is not retrieving from database.Am using MySQL (WAMP) as database.Using Select Query i have checked the data in database and its fine there.When updating the same also its retrieving the old value in db.But when retrieving the value in later stage (ie,taking old bill) its not retrieving the value.The problem is happening only on the single field(ie,actual_price).How to solve this error.Here am attaching the screenshot and controller code for the same.
Controller Code
function bill_view($billid)
{
if(!$billid) {
redirect('report/bill_report');
}
$salecode =str_replace("_","/",$billid);
$filter ="gm_sale.saleCode ='$salecode'";
$billArray =$this->sale_model->getBillinfo($filter);
$exshowroom='';
$bank ='';
$scheme='';
$wcoNo ='';
$saleId =0;
foreach($billArray as $key=>$val) {
$exshowroom = $val['actual_price'];
$date =$val['saledate'];
$sale_to=$val['saleCustomer'];
$saleUserId=$val['saleUserId'];
$wcoNo = $val['wcoNo'];
$saleId= $val['saleId'];
if(!is_null($val['bank']) && !empty($val['bank'])){
$bank =$val['bank'];
}
if(!is_null($val['scheme_id']) && !empty($val['scheme_id'])){
$array_scheme = unserialize($val['scheme_id']);
///////////////////////////////////////////
foreach ($array_scheme as $val_scheme_id) {
$res_scheme = $this->db->get_where("gm_scheme",array('id'=>(int)$val_scheme_id));
if($res_scheme->num_rows >0){
$arrscheme = $res_scheme->row_array();
if(!empty($scheme)) {
$scheme .= ",";
}
$scheme .= $arrscheme['schemeName'];
}
}
/////////////////////////////////////////////
}
break;
}
$query = $this->db->get_where('gm_users',array('userId'=>(int)$saleUserId));
if($query->num_rows >0) {
$arrUser =$query->row_array();
}else{
$arrUser =array();
}
$data['list_product'] = $billArray;
$data['exshowroom']=$exshowroom;
$data['userinfo'] =$arrUser;
$data['saleCode'] =$salecode;
$data['sale_to'] =$sale_to;
$data['added_date'] =$date;
$data['bank'] =$bank;
$data['scheme'] =$scheme;
$data['wcoNo'] =$wcoNo;
$data['saleId'] =$saleId;
$this->load->view('header_login');
$this->load->view('report/bill_view',$data);
//print_r($billArray);
$this->load->view('footer_login');
}
Model Code
function getBillinfo($filter=''){
$this->db->select('*,gm_sale.added_date as saledate');
$this->db->from('gm_sale',FALSE);
$this->db->join('gm_products',"gm_sale.productId=gm_products.productId",FALSE);
$this->db->join('gm_model',"gm_products.model_id=gm_model.id",FALSE);
$this->db->join('gm_banks',"gm_sale.bank_id=gm_banks.bank_id","LEFT");
if($filter<>"")
$this->db->where($filter,'',FALSE);
$this->db->order_by('gm_sale.saleId',"desc");
$query = $this->db->get();
print_r($query);
if($query->num_rows>0) {
$arrRow =$query->result_array();
print_r($arrRow);
return($arrRow);
}
return(array());
}
Your code that you have in the controller doing DB stuff should be in the model.
The controller does not have context to
$this->db
modify your joins (3rd param) to retrieve values in actual_price

Categories