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'].'");
?>
Related
I have checkbox entries that I am appending to a list by their html name, like so:
Choose no more than three categories:<br>
<input id='category1' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asian">Asian
<input id='category2' type="checkbox" name="boxsize[]"
onclick="CountChecks('listone',3,this)" value="asianFusion">Asian Fusion
I have many other checkboxes as well. I then implode this list by doing:
$sanentry=implode(',',$_REQUEST["boxsize"]);
When I echo $sanentry I get a list of the selected values in the following format: asian, asian fusion. However when I try to send these values to my ethnicity table in mysql the ethnicity column is empty. Here is the post method and query I am using to send these values to my table.
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
$sql3="INSERT INTO
ethnicity(restaurant_id,ethnicity)VALUES('$sanrestid','$sanethnicity')";
if ($con->query($sql3) === TRUE) {
echo "New record in ethnicity table created \n";
} else {
die("Error: " . $sql3 . "<br>" . $con->error);
}
mysqli_close($con);
?>
There is no problem with my restaurant_id column as that is being updated fine but for every new row inserted the ethnicity column always comes up blank. Does anyone know what I'm doing wrong?
enter image description here
Guessing the variable name is wrong. should be $sanethnicity you've got $ethnicitydb in your query.
$sql3="INSERT INTO ethnicity(restaurant_id,ethnicity) VALUES('$sanrestid','$sanethnicity')";
Also, is this the field that has raw ethicity array? $_POST['$sanentry'] or has that been imploded. You probably want this:
$sanethnicity=mysqli_real_escape_string($con, $sanethnicity);
Since the $sanethnicity was prior imploded from seomthing like:
$sanethnicity = implode(',',$_REQUEST["boxsize"]);
In this line your trying to use $sanentry as an entry in $_POST...
$sanethnicity=mysqli_real_escape_string($con, $_POST['$sanentry']);
Should be
$sanethnicity=mysqli_real_escape_string($con, $sanentry);
Although - you should be looking into using prepared statements and bind variables.
If you want to store it without losing the array structure then you should use serialize
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)
I have a huge multistep form with data for multiple tables in mysql db. For every field my html is like-
input type="text" name="names" value="" // value set using php echo
On submit at php I am doing this for all the fields of my form-
$name=$_POST['names'] ?? ' '
to avoid unidentified index and unidentified variable
Then i update my first table and write log that its updated.
$query=mysqli_query($con,"UPDATE teacherpersonal set name='$name' ... where id=$id");
write_mysql_log("teacherpersonal updated", "facultydetails", $id).
I have defined write_mysql_log.
And similarly i update all the remaining tables with either the updated values or blank ("") values.
Since you can see that update query always executes even if the fields are not changed. Hence it is always logged that the tables are updated. But that's not what I want. I want to update only those fields in the table which are changed and remaining stay intact and log only those tables which are thus updated. Many tables won't be updated this way as the user might change only few details.
Using jquery and php.
My write_mysql_log is
function write_mysql_log($message, $db, $faculty_id)
{
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"facultydetails");
// Construct query
$sql = "INSERT INTO my_log (message, faculty_id) VALUES('$message', '$faculty_id')";
$query=mysqli_query($con, $sql);
// Execute query and save data
if($query) {
echo 'written to the database';
}
else {
echo 'Unable to write to the database';
}
}
This you can achieve in 2 different ways.
1) With the help of jQuery check the values which are updated, post only those values to the php script
2)At the time of updating the check the current values with the updated one based on that criteria update the db tables.
solution 1 is less time taking process compare to the other.
You need to update only the user edited value, by doing this you can achieve it;
$oldvalue = array("username" => "green", "email" => "green#mail.com","dob" => "111");
$newvalue = array( "email" => "green#mail.com","dob" => "111","username" => "blue");
$updates = array_diff($newvalue, $oldvalue);
$implodeArray = implode(', ', $updates);
$sql = ("UPDATE user WHERE userID=$userID SET $implodeArray");
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
Output:
$updates = array_diff($newvalue, $oldvalue);
will have:
Array ( [username] => blue )
which is changed one
Ok after considering many options like-
create json object for old and new data and then compare and check which values changed and update that table and log it.
Or create a php array with old and new data and check diff then do the same (as suggested by Ram Karuppaiah)
Or a bad idea to have a flag on every input and then mark which ones have changed using onkeyup jquery event then try to update only those fields tables.
So finally what i did is that i let the form get submitted with all the data. As earlier i am taking the data in php as $name=$_POST['names'] ?? ' ' (blank if nothing is submitted or if something submitted then its value).
Before update statement in php, i am querying the table and comparing the database values with the values i got, if all same i dont do anything. If not then i update the table with the new values and log the change.
Here is a function I have in my php file
function deleteLocation() {
global $con;
$val = $_POST['id'];
$escaped = mysqli_real_escape_string($con,$val);
$sql = "DELETE FROM settings WHERE value = '".$escaped."'";
if(!mysqli_query($con,$sql)){
die("Query failed:" . mysqli_error($con));
} else {
die("DELETE FROM settings WHERE value = '".$escaped."' / num rows affected: " . mysqli_affected_rows($con));
}
}
Here is the text that is returned on the page
DELETE FROM settings WHERE value = 'asdasd ' / num rows affected: 0
If I take the first part, and run it on my phpmyadmin page,
DELETE FROM settings WHERE value = 'asdasd '
it will correctly delete the row, but as you can see from the output, 0 rows are affected when the script is run on the page.
If anyone can help to fix this I will be very grateful.
PS: The connection string and user permissions are indeed set up correctly, because every other function in this file works properly
EDIT: Got it, the space at the end of the string was a newline character that was sent from my javascript.
I tried re-creating your problem on my machine and the only time I get the same message as you is when that item was already deleted from the table (or when it wasn't there in the first place)
This was a pretty unique situation, so I don't know how much this would help other people but,
I had an array of strings that all had \n at the end, so I had to do
str[value] = str[value].trim();
foreach value in the array. It turns out that this was not a php problem, but rather js
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.