Array php and database mysql saving datas - php

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.

Related

Why does POST value save empty in database, but var_dumps / echos fine?

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!";
}
?>

Accessing records with same name but different ID

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)

php mysql issue with check if record exist before insert

I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.

error grabbing ad code from database using mysql

I am trying to grab ad code from my database and echo it on to the page, but for some reason it is not showing up?
$getad = ("SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ");
while($rows = mysql_fetch_array($getad))
{
$code = $rows['code'];
}
$ad1 = $code;
later down the page i print it like this.
<?php print $ad1 ?>
I think your problem is that you don't actually execute the query, you just have saved it in a variable ($getad) and then try to do a fetch af an array containing a string as I see it. If I remeber correctly you have to save you query in a variable, as you did, and then type
$getad = "SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ";
$q = $db->query($getad);
// generate results:
while ($q->fetchInto($row)) {
//display or store
}
You should also include checks, for example that this code has extracted at least one row, or that database connection is working, etcetera.

Insert multiple data as well as update in database using php?

I get Nearest 50 km location names from current location using google api, so it' works fine.
So I need to insert all these locations into my database. If some location already there in database, I need to update these location.
For example I get 10 locations in google api so 5 locations are already there in my database. I need to 5 location are update and remaining 5 locations are insert.
Here is my code:
<?php
require 'dbconnect.php';
$LocaName=$_REQUEST['locname'];
$address=$_REQUEST['address'];
$latt=$_REQUEST['Latt'];
$long=$_REQUEST['Long'];
if($latt && $long)
{
$LocaNamearray = explode("|||", $LocaName);
$addressarray = explode("|||", $address);
$lattarray=explode("|||",$latt);
$longarray=explode("|||",$long);
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
}
if($now >=1)
{
for($k=0;$k<count($lattarray);$k++)
{
$query="update tbl_MapDetails set LocationName='".$LocaNamearray[$k]."', Address='".$addressarray[$k]."',Latitude='".$lattarray[$k]."', Longitude='".$longarray[$k]."' where Latitude='".$lattarray[$k]."'and Longitude='".$longarray[$k]."'";
}
$nav="update";
}
else
{
$query ="INSERT INTO tbl_MapDetails(LocationName,Address,Latitude,Longitude) VALUES";
$strDelimiter = "";
for($j=0;$j<count($LocaNamearray);$j++)
{
$name =$LocaNamearray[$j];
$address =$addressarray[$j];
$lat = $lattarray[$j];
$long = $longarray[$j];
$query .= $strDelimiter."('$name', '$address','$lat','$long')";
$strDelimiter = ',';
}
$nav="Add";
}
$result= mysql_query($query);
if($result)
{
echo mysql_error();
$message=array("message"=>"sucessfully".$nav);
}
else
{
echo mysql_error();
$message=array("message"=>"fail".$nav);
}
}
else
{
$message=array("message"=>"require latt and long");
}
echo json_encode($message);
?>
Here insert and update working but I need to check every location in database. There is no location in database. It need to insert other location are update. how to check both these conditions matched locations are update and unmatched locations are inserted Please guide me.
Your logic is wrong in the code. What you are doing is looping through the provided data and for each set of data checking if a location with that lat/long exists and storing it in the $now variable. Once you've finished that loop, you're then checking $now and looping through the provided data again and either INSERTing or UPDATEing each set of data. So if the last set of data exists, your script will try and UPDATE each set of data. If it doesn't, your script will try to INSERT each set of data. Your code should be something like this (mixture of your code and pseudo-code):
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
if($now >=1)
{
// update table with location details
}
else
{
// insert location details into table
}
}
If this becomes a performance issue you could look at retrieving all the SELECT data first but if you're only dealing with 10 rows at a time you should be OK.
Note: depending on where your $_REQUEST data is coming from you might want to do some validation, i.e. to check you have matching sets of lat/long/name/address details.
Take a look at MySQL`s ON DUPLICATE KEY UPDATE. But you must be careful, because it is quite slow operation.
But, I think, it would be better if you just union all your SELECT requests in one using OR conditions.

Categories