I try to insert one person detail, it's inserted successfully. If i check in DB "same data insert 3 times". Why the data insert 3 times?
I had this data in the Database.
id name dob gen
1 James 12-03-1977 M
2 James 12-03-1977 M
3 James 12-03-1977 M
PHP class
class Detail
{
function savePerson_detail($vars){
foreach($vars as $key => $value){
if(is_numeric($key) && $value >0){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{
print 'Successfully Insert your details';
}
}
}
Html Page
<?php
$detail = new Detail();
if(isset($_POST['btnSaveDetail'])){
$detail->savePerson_detail($_POST);
}?>
You actually run the query three times, that is why you insert the data three times. Just run the query one time and you should be fine.
To do this you need to change your code: First sanitize the input data in full, then run the query. You are currently picking each element of $vars (which has three elements) and then you run the query each time.
Do one step after the other:
function savePerson_detail($vars)
{
// validate function input
foreach($vars as $key => $value)
{
if(!is_numeric($key) || !$value >0)
return;
}
// build sql query
$qry = sprintf(
"INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')",
mysql_real_escape_string($vars['name']),
mysql_real_escape_string($vars['dob']),
mysql_real_escape_string($vars['gen'])
);
// run sql query
$result = mysql_query($qry) or die(mysql_error());
// check query result
if($result)
{
print 'Successfully Insert your details';
}
}
Because you used
foreach($vars as $key => $value){
When $vars or $_POST which was passed to it looks like this.
$_POST['name'] = 'James';
$_POST['dob'] = '12-03-1977';
$_POST['gen'] = 'M';
So it went through each of your $_POST items 3 times.
I think you can remove the validation and do it like this.
function savePerson_detail($vars){
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')", mysql_real_escape_string($vars['name']), mysql_real_escape_string($vars['dob']), mysql_real_escape_string($vars['gen']));
mysql_query($qry) or die(mysql_error());
if($qry)
{ print 'Successfully Insert your details'; }
}
Unless I'm missing something, is this what you're trying to do?
class Detail
{
function savePerson_detail($vars) {
foreach($vars as $key => $value) {
$vars[$key] = mysql_real_escape_string($value);
}
if($qry)
{
print 'Successfully Insert your details';
}
$qry = sprintf("INSERT INTO cca_student_list(per_name, per_dob, per_gen) VALUES('%s', '%s', '%s')";
mysql_query($qry) or die(mysql_error());
}
Related
I need to execte both querys, but insertion will happen on one table(first query only). If i put query9 first, it will execute, otherwise query3.
$query9 = $con->prepare("INSERT INTO complete_status (ID, hotel_id,
floor_id, room_id, pull_chrdsw_status, emergency_status, nurse_callsw_status, cmr_status, foodsw_status, bedside_cancelsw_status ,nurse_distress_status, bcssw_status ,final_status,date1, Time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)");
$query9->bind_param("iiiiiiiiiiiii", $ID, $HotelID ,$SectorID, $RoomID, $pull_chrdsw_status, $emergency_status, $nurse_callsw_status, $cmr_status, $foodsw_status,$bedside_cancelsw_status, $nurse_distress_status, $bcssw_status,$statuss);
if($value->NurseCallSwStats != $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats)
{
if($DebugMode===TRUE)// Test mode with debugg outputs
{
echo "<br>";
echo "laundry change";
}
$Difference_Flag=TRUE;
$nurse_callsw_status = $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats;
$query3->execute();
$query9->execute();
}
foreach ($Uploadedpkt->RoomStatus as $key => $value)
{
$nurse_callsw_status = $Uploadedpkt->RoomStatus[$key]->NurseCallSwStats;
$query3->execute();
$query9->execute();
}
you can create a stored procedure that contains all your queries and then execute it.
Im trying to get the ID when I insert a SQL, I've tried to get the last. I've tried to echo out the ID in the hidden html form but without any success
As you see I've $sql that inserts INTO log_create, but from that I need to receive the ID which is created, it need to be echoed
$id = $db->real_escape_string(trim($_POST['id']));
$name2 = preg_replace('/\s+/', '', $name);
$game = $db->real_escape_string(trim($_POST['game']));
$info = $db->real_escape_string(trim($_POST['info']));
$mobname = $db->real_escape_string(trim($_POST['mobname']));
$sql = "INSERT INTO log_create(`id`, `name`, name2, game, monster, info)VALUES('$id', '$name', '$name2', '$game', '$mobname', '$info')";
if($result=$db->query($sql))
{
$log = $db->query("SELECT itemname FROM `log_mitem` WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
if($log1 = $log->fetch_object());
{
while($loco = $log->fetch_object())
{
$item = "$loco->itemname";
$logss = "INSERT INTO log_drops(`item`, `mobname`, `game`, `log_id`, `log_name`)VALUES('$item', '$mobname', '$game', '$id', '$name')";
if($result1 = $db->query($logss));
}
}
echo '<p>';
echo 'Your droplog has been created! Check your droplog category to start hunting!';
echo '</p>';
} else { echo 'Something went wrong!';
}
Thismay help you, maybe?
Good luck! :-)
EDIT: My bad, I should have said what was that, instead of linking directly.
It's the mysqli::$insert_id variable.
It stores the last ID created by the last used "INSERT" sentence.
...
if($result=$db->query($sql))
{
echo "New ID: "+$db->insert_id+"<br />";
...
Or wherever you want to use it.
Make sure to store it before inserting anything else, or it'll be replaced.
I almost managed to split the different arrays and to prepare them in the table in the MySQL database, I'll explain the situation:
On the main page, the user has the ability to add and remove rows in a table. The table for each line carries with it these inputs:
input1.name = "product[]";
input2.name = "seller[]";
input3.name = "description[]";
input4.name = "quantity[]";
input5.name = "priece[]";
so if the user inserts two rows in each array will be included descriptions of two products, for example:
product: "PS3", "PS4";
seller: "AMAZON", "SONY";
description: "100Gb", "200Gb";
quantity: "1", "2";
price: "100", "200";
This is the layout table:
http://www.mediafire.com/view/ux0su8ssdixfmgc/Cattura2.JPG
The problem arises. I capture the data entered via a post, but I can't distribute these data on several lines. I want you to PS3 both into the first row of MySQL table, and PS4 in the second row of the table. Until now arrays are instantiated only on the first line, in this way, however, there is only one product. It is therefore necessary to prepare each box in the appropriate row of the array. I do not know if I was clear, but I would like to achieve something like this:
http://www.mediafire.com/view/d6f6ahy834jv0p2/Cattura.JPG
Obviously, the data in table I've entered manually and not through code. Was it right for you to understand.
This is the code that I currently use to send multiple arrays on different lines, but it doesn't work.
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
$row_data[] = "('$product', '$seller', '$description','$quantity', '$priece', '$user')";
}
if (!empty($row_data))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.implode(',', $row_data);
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
if I understood it well this is how it should work
if(isset($_POST['sending']))
{
if($_POST['sending'] == "save")
{
$row_data = array();
foreach($_POST['sending'] as $key => $value)
{
$product=mysqli_real_escape_string($con,($_POST['product'][$row]));
$seller=mysqli_real_escape_string($con,($_POST['seller'][$row]));
$description=mysqli_real_escape_string($con,($_POST['description'][$row]));
$quantity=mysqli_real_escape_string($con,($_POST['quantity'][$row]));
$priece=mysqli_real_escape_string($con,($_POST['priece'][$row]));
$user=mysqli_real_escape_string($con,($_POST['user'][$row]));
array_push($row_data, "('$product', '$seller', '$description','$quantity', '$priece', '$user')");
}
foreach($row_data as $value){
if (!empty($value))
{
$sql = 'INSERT INTO test(product,seller,description,quantity,priece,user) VALUES '.$value;
$result = mysqli_query($con, $sql );
if ($result)
echo 'ADD COMPLETE!: ' . mysqli_affected_rows($con);
else
echo 'ERROR' ;
}
} // if ($_POST['sending'] == "save")
} // if (isset($_POST['sending']))
}//close method
sorry for the complicated heading.i am doing learning php and got stuck.i have a database table table_name
id(primary key) name ip
1 a 192.168.0.1,192.168.0.5,171.87.65 //separated by comma's
2 b 192.168.0.1,175.172.2.6,164.77.42
now i want to add an array of values ip[0] and ip[1] coming from a two different text-area to the end of the ip's of each name and just updating the ip column of each row.so it will just append new values with previous one.
name a<textarea rows="4" cols="40" name="ip[]"></textarea>
name b<textarea rows="4" cols="40" name="ip[]"></textarea>
<input type="submit" />
this is how its inserted
if(isset($_POST['submit'])) {
$ip_details = $_POST['ip'];
$values = array(
array('id' => '"1"', 'name' => '"a"', ip => '"'.$ip_details[0].'"'),
array('id' => '"2"','name' => '"b"', ip => '"'.$ip_details[1].'"'),
);
$columns = implode(', ', array_keys($values[0]));
foreach($values as $value) {
$value = implode(', ', $value);
$statement = "INSERT INTO `center_listt` (id,name,ip) VALUES ($value)";
$res=mysql_query($statement);
echo "success";
}
}
i need to update each rows of namea and b with new values coming from text-area with previous values.
i am thinking of array_push after fetching ip from table in while loop but could not really do it.warning: array_push expects parameter 1 to be array integer given its because the $row['ip'] fetched in while loop is not valid array which array_push expects.
and it will only add new values in different new rows each time which i don't want.can someone please help what to do.
<?php
if(isset($_POST['submit'])) {
//print_r($ips); die;
$i = 0;
foreach($_POST['ip_details'] as $ipaddr) {
$ips[$i] = $ips[$i].$ipaddr;
$i++;
}
$r = 1;
foreach($ips as $ip){
//echo "UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'"; die;
if(mysql_query("UPDATE center_listt SET ipdetails = '$ip' WHERE `id_center` = '$r'")) echo "IP Address Updated <br />";
else echo 'error occurred';
$r++;
}
}
$sql="select * from center_listt";
$res=mysql_query($sql);
if(!$res) {
die('could not connect'.mysql_error());
}
while($row=mysql_fetch_assoc($res))
{
echo $row['ipdetails']; }
?>
its a bad practise to insert form values from array.you can fetch it from db bcoz if in future you want to add new form values you need to rewrite again with array values while fetching from db will only need you to insert new values in db.
my query will add ip's in your specific column in a single row only updating the ip with new values.
You could do this:
$values = array(...); // WARNING: escape `$ip_details` here!!
$to_insert = array();
foreach($values as $row) {
$to_insert[] = "(".implode(", ",$row).")";
}
$statement = "insert into `center_listt` (`id`, `name`, `ip`)
values ".implode(", ",$to_insert)."
ON DUPLICATE KEY UPDATE `ip`=concat(`ip`,',',values(`ip`))
";
mysql_query($statement);
This will perform a multi-insert (far more efficient than individual queries), and when you try to insert the same ID twice it will instead concatenate the values.
It should be noted that this is bad database design, though :p
I hope my title isn't completely confusing. I'd like to start by saying I am in now way a programmer and am an amateur with PHP and MySQL, which I use for online gaming. I have been tirelessly working at this for a few days, with no success. I've been toying with the idea of asking for help here, hoping folks go easy on me and don't completely rip apart my code! Like I said, I'm an amateur.
Basically, what I'm trying to do is match the $horsename data from my $_POST array with name in my table called horses. If they do not match it will add a horse with that name into the horses table. If they do match, it will simply continue on and add the data from the $_POST array into the results table for each line.
The issue I'm getting, (and I've toyed with this multiple times, with a different issue arising each time) is even if the $horsename matches name in the horses table, it tries to add a new horse into the horses table. It also is not moving onto the next line of data and will try to add the same horse over and over again. (Hope that makes sense!)
I'm pasting most of my code from this page below, just in case it's something earlier in my code causing this issue. Please note, a portion of this code is not my own and I am working on it for someone else, so if things are not completely uniform in a couple of spots, that is why. The portion I'm working on is what I've mentioned above.
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$results = str_replace("\r", '', trim($_POST['news']));
$data = array();
$lines = explode("\n", $results);
foreach ($lines as $place) {
if (!empty($place)) {
$data = array();
$detail = explode(",", $place);
if (!empty($detail)) {
$id = '';
$show = $_POST['show'];
$year = $_POST['year'];
$association = $_POST['association'];
$chpoints = $_POST['chpoints'];
$rchpoints = $_POST['rchpoints'];
$ttpoints = $_POST['ttpoints'];
$chearnings = $_POST['chearnings'];
$rchearnings = $_POST['rchearnings'];
$ttearnings = $_POST['ttearnings'];
$horsename = stripslashes(trim($detail[0]));
$placement = stripslashes(trim($detail[1]));
$class = stripslashes(trim($detail[2]));
if($placement === 'CH'){
$points = $chpoints;
}
else if ($placement === 'RCH') {
$points = $rchpoints;
}
else {
$points = $ttpoints;
}
if ($placement === 'CH') {
$earnings = $chearnings;
}
else if ($placement === 'RCH') {
$earnings = $rchearnings;
}
else {
$earnings = $ttearnings;
}
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
if (isset($_POST['news'])) {
$query="INSERT INTO `results` (`id`, `show`, `year`, `place`, `name`, `class`, `points`)
VALUES ('$id','$show','$year','$placement','$horsename','$class','$points')";
mysql_query($query) or die ('Error updating database: ' . mysql_error());
echo "Result successfully added!" ;
}
};
};
};
To take a snip-it from above, this is the place I'm having the issues:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
If anything from the page where news is coming from is needed, please let me know.
Thanks in advance!
The problem is that you are querying the database for a list of every horse name. You're iterating through that list and each time the names don't match, you're inserting the new name. What you need to do instead is to query for the specific name.
SELECT * FROM horses WHERE name = '$horsename'
If this returns a row, then you know the horse is already in the database. If it returns no rows, then you can safely insert once. By the way, you'll want to properly escape your input to prevent SQL injections so don't use my code verbatim.
Try this:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
$i = 0;
$horsename = "";
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
$i = 1;
}
}
if($i == 1) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}