I am handling a database table, where I have a quantity field in it. The quantity is manipulated through a form where it is reduced. The record gets inserted in the table with the new value as a new record with new quantity(reduced) and through this table it is being fetched in the next form. Now the issue is that whenever I fetch the quantity the older record(record with original quantity) is fetched where as the record with new quantity should be fetched.
I tried updating the same record with new value but it is not updating.
Here is the code for the same :
$haha="SELECT quantity FROM ready_for_delivery WHERE joborderid='".$data['joborderno']."'";
$haharesult = mysqli_query($link,$haha);
if(mysqli_num_rows($haharesult)>0)
{
$sql1="UPDATE ready_for_delivery SET quantity='".$_POST['rp_qty']."' WHERE joborderid='".$_data['joborderno']."'";
$sq1result=mysqli_query($link,$sql1);
//echo "I am here";
}
else
{
$quantity="INSERT INTO `ready_for_delivery` (`joborderid`,`joborderdetailsid`,`datetime`, `quantity`) VALUES ('".$data['joborderno']."',' ', now(), '".$_POST['rp_qty']."');";
$res1 = mysqli_query($link,$quantity);
echo "done";
}
I am checking if there is any data in the table with specified job order no, if yes, update it else insert as a new record. Every time it inserts as new record. Please guide me. Thanks.
Remove ; from your first line, hope this will work .
$haha="SELECT quantity FROM ready_for_delivery WHERE joborderid='".$data['joborderno']."'"; //remove ;
//echo $haha;
$haharesult = mysqli_query($link,$haha);
if(mysqli_num_rows($haharesult>0))
{
$sql1="UPDATE ready_for_delivery SET quantity='".$_POST['rp_qty']."' WHERE joborderid='".$_data['joborderno']."'";
$sq1result=mysqli_query($link,$sql1);
//echo "I am here";
}
else
{
$quantity="INSERT INTO `ready_for_delivery` (`joborderid`,`joborderdetailsid`,`datetime`, `quantity`) VALUES ('".$data['joborderno']."',' ', now(), '".$_POST['rp_qty']."');";
$res1 = mysqli_query($link,$quantity);
echo "done";
}
In the mysqli_query you have $sql a query variable while the actual query is in the $haha var.
Also, did you check if variable $data['joborderno'] is not empty?
The error lies in this line of code:
if(mysqli_num_rows($haharesult>0))
the closing brackets is in the wrong place. Correct way:
if(mysqli_num_rows($haharesult)>0)
Related
I have a contact list that I made with PHP, jQuery and Datatables, where I have inline editing, and as soon as you click outside of a cell it updates via Ajax. Everything about the update of field values work fine, but now I wanted to save who last updated a record, by saving the username from the current session, so I've done that and sent it to the update file as a $_POST, but it won't save. When I dump it out or echo it, I can see the value, so I know it does get posted, but it just won't save in the database and I can't figure out why.
Since I don't code a lot and have learned what I know by reading and copying stuff from Stackoverflow, I'm sure I'm missing something obvious, but I still need help and I want to learn.
I've tried all kinds of "' variants, and typing in "test" or something in the query or in the variable does save it, so I feel like something is wrong with the $_POST or sql syntax, but since I can dump it and echo it, I have no idea what's wrong.
Worth mentioning is that the first part of the SQL works fine, and updates the cell it's supposed to, so the query runs, but randomly returns either "Uppdaterad!" or "Invaild requests" every other time, but the value saves either way. If I remove the whole "new part" with "last updated by", it works every time and returns "Uppdaterad!" without any problems.
<?php
if(!empty($_POST))
{
// Database settings
include "config.php";
foreach($_POST as $field_name => $val)
{
// Clean post values
$field_contactid = strip_tags(trim($field_name));
$val = strip_tags(trim(mysqli_real_escape_string($con, $val)));
$currentuser = strip_tags(trim(mysqli_real_escape_string($con, $_POST['currentuser'])));
//var_dump($currentuser);
// From the fieldname:contact_id we need to get contact_id
$split_data = explode(':', $field_contactid);
$contact_id = $split_data[1];
$field_name = $split_data[0];
if(!empty($contact_id) && !empty($field_name))
{
// Update the values
mysqli_query($con, "UPDATE contactlist SET $field_name = '$val', `last_updated_by` = '$currentuser' WHERE id = $contact_id") or mysqli_error($con);
//mysqli_query($con, "UPDATE contactlist SET $field_name = '$val' WHERE id = $contact_id") or mysqli_error($con);
echo "Uppdaterad!";
} else {
echo "Invalid Requests";
}
}
} else {
echo "Empty POST!";
}
?>
Im trying to insert multiple data that has only been selected checkbox. But Unfortunately, It also inserted the the unselected checkbox and also getting duplicate data.
Here's the UI for selecting data.
Here's my code:
if(isset($check)){
$client = $_POST['client'];
$project = $_POST['project'];
$kit_no = $_POST['kit_no']; //array
$kit_desc = $_POST['kit_desc']; //array
for($i=0;$i<sizeof($check);$i++){
for($i=0;$i<sizeof($kit_no);$i++){
for($i=0;$i<sizeof($kit_desc);$i++){
$query=mysqli_query($con,"INSERT INTO tbltrainsets_kit(id, client, project, kit_no, kit_desc)VALUES(
'',
'".$client."',
'".$project."',
'".$kit_no[$i]."',
'".$kit_desc[$i]."'
)")or die(mysqli_error($con));
}
}
}
}
The output that I produce is like this: (Please see the actual pix below):
The unselected data ('NA') was inserted into the database. It should only be the item 'DTR4000037253' inserting into the database.
Thank you in advace. Please respect my questions. I'm still studying do please do not bash. :|
I found the solution for this. When I study my code I realized that all of the logic is wrong.
Here's my code:
if(isset($check)){ // verify if checkbox is checked
foreach($check as $selected){ // select each checkbox that was selected an
// select value from the column equal to the ID of the selected checkbox
$kit_no = $this->dbquery->modGetdynamicval('tblkit','id', $selected, 'kit_no');
$kit_desc = $this->dbquery->modGetdynamicval('tblkit','id', $selected, 'kit_desc');
$query=mysqli_query($con,"INSERT INTO tbltrainsets_kit(id, client, project, kit_no, kit_desc)
VALUES('', '".$client."','".$project."','".$kit_no."','".$kit_desc."')")or die(mysqli_error($con));
echo $selected."</br>";
echo $kit_no."</br>";
echo $kit_desc."</br>";
}//end for loop
I'm using CI framework for getting the value the other 2 variables that I want to insert.
I have a mysql table with a field called points and that value is 19. When i change the value using:
<?php
$con=mysqli_connect("blah", 'blah', 'blah', "blah");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Social_points (`points`)
VALUES
('$_POST[Jpoints]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Which read the form data from a previous page it works fine however it merely adds the value to the end of the original value for e.g. if i had 19 as original value and then entered 5 in the form it would change to 195. Any ideas
If You have to add value as new record then use INSERT query otherwise use UPDATE query.
Use the UPDATE syntax and not insert..
$sql="UPDATE Social_points set (`points`)
VALUES
('$_POST[Jpoints]')";
Try this mate
update social_points set points = convert(varchar(5),points)+'5'
This is just a wild stab in the dark:
You're using the POST method, so I guess you're calling that script via AJAX. And my next guess is, you probably do the addition of the original value and the new value with Javascript, before the form gets sent.
So what probably happens in Javascript is this:
Instead of adding both values, they are concatenated and then sent to the DB, being treated as a string (JPoints).
If i'm right, you need to cast both values to int in your Javascript.
read the data from database.
for example you add an item
take the ID of last added item and update it.
<?php
// before this you have a query for last added item.
$data['itemid'];
$_POST['newvalue'];
$data['value'];
//if the value 19 and the new value 5 this will become 195
$newvalue = trim($data['value'] . $_POST['newvalue']);
$sql->query("UPDATE tablename SET value = '.$newvalue.' WHERE itemid = '.$data['itemid'].'");
?>
I'm having trouble with an array. It actually appears on a page: a form of several lines. Each line corresponds to a record in the database and so they all have a common denominator.
More thanks to javascript I can add fields on the fly.
The trouble I'm having is when recording data. In fact I thought at first I should delete everything, and then insert so I just the following query:
<?php if(isset($_POST['enreg']))
{
foreach($_POST['data'] as $data){
if (!empty($data['code_s'])){
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);
$sql7 = '
INSERT INTO scenarii SET
code_s = "'.mysql_real_escape_string($data['code_s']).'",
titre = "'.mysql_real_escape_string($data['titre']).'",
action = "'.mysql_real_escape_string($data['action']).'",
libelle = "'.mysql_real_escape_string($data['libelle']).'",
jour = "'.mysql_real_escape_string($data['jour']).'"' ;
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);
}
}
}
?>
The worries is that the deleted information is not stored again (though they are in the post variable as they exist in the form of a form and are therefore the variables.
In fact it only saves the new rows from javascript.
The trouble is that I can not do an update just because there are new lines.
<?php if(isset($_POST['enreg']))
{
$sql2="DELETE FROM scenarii WHERE code_s='".mysql_real_escape_string($_GET['code_s'])."'";
mysql_query($sql2) or die(__LINE__.mysql_error().$sql2);
foreach($_POST['data'] as $data){
if (!empty($data['code_s'])){
$sql7 = '
INSERT INTO scenarii SET
code_s = "'.mysql_real_escape_string($data['code_s']).'",
titre = "'.mysql_real_escape_string($data['titre']).'",
action = "'.mysql_real_escape_string($data['action']).'",
libelle = "'.mysql_real_escape_string($data['libelle']).'",
jour = "'.mysql_real_escape_string($data['jour']).'"' ;
mysql_query($sql7) or die(__LINE__.mysql_error().$sql7);
}
}
}
?>
put your delete query before foreach loop
afeter several hours of testing Ive seen that the delete request was in the loop for each so it has deleted all after all reinjection that is why I only have the last input left evry time.
Now I've deleted all and reinjected all after. It works properly.
What I do not understand is that i did not see it before.
Thanks to everybody for the help.
I have a PHP script that inserts data into a mysql database. The table has an auto increment column.
I want to use the mysql_insert_id() function to get teh value of the last inserted record.
For some reason this is returning the value 0 where the autoid column has a value of 300037.
Any assistance is appreciated. Thank you.
my code snippet is below:
$sqlinsertdelivery="INSERT INTO deliverydetails (`LoadID1`,`deliveryroute`,`source`,`destination`,`route`,`CollectionArea1`, `CollectionArea2`, `CollectionArea3`, `CollectionArea4`, `CollectionDate`, `collectiontime`, `Destination1`, `Destination2`, `Destination3`, `Destination4`, `ArrivalDate`, `ArrivalTime`, `DeliveryCreationDateTime`, `DeliveryCreatedBy`,`comments`,`trailertype`)
VALUES
($loadnumber,'$route1','Hulamin','$dest1','$_SESSION[sessionrouteid]','$_POST[dispatchid1]','$_POST[dispatchid2]','$_POST[dispatchid3]','$_POST[dispatchid4]','$_POST[coldatetime]','$_POST[deltime]','$_POST[drop1]','$_POST[drop2]','$_POST[drop3]','$_POST[drop4]','$_POST[arrivedatetime]','$_POST[arrivetime]',CURRENT_TIMESTAMP,'$session->username','$_POST[comments]','$_POST[vehicletype]')
";
if (!mysql_query($sqlinsertdelivery,$con))
{
die('Error with insert statement: ' . mysql_error());
}
$delid = mysql_insert_id();
echo $delid;
Long shot, but first try replacing mysql_insert_id(); with mysql_insert_id($con);
On a side note, PLEASE tell me this is code that will not be in production.