I have values written in a database. These value come from a checkbox form.
I try to get these values from the database and write them in a new page.
I use the following code that works :
$con = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$pw") or die ("Error in Selecting ");
$sql = pg_query($con,"SELECT language FROM texte where bhl='17'");
if(pg_num_rows($sql) > 0){
$result = pg_fetch_assoc($sql);
$checked_arr = explode(";",$result['language']);
}
// Gives "item1"
// Create checkboxes
foreach ($checked_arr as &$value) {
$array1 = array("item1", "item2", "item3");
// insertion of the id's corresponding to item1, item2, item3
$id = array("id-item1", "id-item2", "id-item3");
$checked = "";
if(in_array($value, $array1)){
$checked = "checked";
}
echo '<input type="checkbox" name="lang[]" value="'.$value.'" '.$checked.' > '.$value.' <br/>';
}
But actually something is missing : the id value that characterizes the checkbox. So I inserted in the code an array composed of the id values.
The goal is to associate id-item1 to item1, id-item2 to item 2 and so on.
To make it possible I guess I have to create a double loop to write in the echo statement both values and id's.
But after many attempts I didn't manage to make it possible and I really don't know how I could do.
Any help would be appreciated.
Thanks !
Related
Can anybody tell me what I'm doing wrong i want to update my Mysql table with 3 rows. I Selecting checkboxes and i press button then nothing happend with upadate of table. It's saving good id's to array, but update query doesen't work.
$s = mysql_query("SELECT data.id, data.sonda_data, data.type, odp.id, odp.sonda_data, odp.type, odp.wyniki, odp.idp FROM data,odp WHERE data.id=odp.idp");
$i=0;
$tab= array();
while ($row = mysql_fetch_row($s))
{
if ( (isset($_POST['pole'.$row[3]])) && (!isset($_SESSION['security'])) )
{
$id = $_POST['pole'.$row[3]]; // get id from radio boxes
$tab[i]=$id; // saving radio boxes id's to array
$i++; // increment array
// array look like example 8,11,10
if($i==3)
{
while($i>=1)
{
mysql_query("UPDATE odp SET wyniki = (wyniki + 1) WHERE 'id=$tab[$i]'");
$i=$i-1;
}
$_SESSION['security'] = true;
}
}
}
I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."
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 am allowing user to create up to ten categories using text boxes in a form. To do this I have ten textboxes in the form with name = cat[]. The first time they enter categories--however many, up to ten, on the receiving end, I just collect the array of categories and save them to a table of categories using an insert statement. So far so good.
However, now I want to let them change categories they already set or add extras up to ten total. The categories they already set have ids. So I echo the ids to the form along with the category names. My problem is how do I collect the names and ids now? New ones need to be inserted and existing ones may need to be updated in the table? For some reason, I'm at a total loss how to do this. This is what I have so far>
Table Cats
id | catname | userid
Form page:
//retrieve existing cats if any...also get catids
echo '<form action = storecats.php method=post>';
$i=1;
//Get all existing cats
while($row = mysql_fetch_array($res))
{
$catname = $row['catname'];
$catid = $row['id'];
echo '<input type = "text name="cat[]" value="'.$catname.'">Cat 1';
echo '<input type="hidden" name="id[]" value = "'.$catid.'">';
$i = $i+1;
}
//empty boxes up to ten.
while($i <= 10){
echo '<input type="text" size=18 name="cat[]" value=""> Cat '.$i.'<br>';
$i = $i+1;
}//end appending of blank categories
echo '<input type="submit" name="submit" value="submit"></form>';
On receiving end, I can collect the array for cat and id.
$idarray = $_POST['id']; //there will be as many elements as there were ids
$catarray = $_POST['cat']; //there will be ten elements in array
Where there is an id, I want to perform an update whereas where there is no id I want to insert unless the value is blank.
My problem is I can't figure out how to link the id and the cat names being received in the different arrays. Note, there will always be ten cat names but there will only be as many ids as were in the table for that user previously.
You can do it with 2 array on HTML side:
$x=0;
while ($row = mysql_fetch_array($res))
{
echo '<input type="text" name="updateCat['.$row["id"].']" value="'.$row["catname"].'"> Cat Name';
$x++;
}
// new ones
for(;$x<10;$x++)
{
echo '<input type="text" name="newCat[]">';
}
and on php side:
// update old categories
foreach ($_POST["updateCat"] as $key => $value)
{
mysql_update ("UPDATE table SET name = $value WHERE id = $key");
}
// insert
foreach ($_POST["newCat"] as $value)
{
mysql_update ("INSERT INTO table {...}");
}
You have also check that there are not more than 10 Categories when inserting new ones.
Name the inputs which are for existing categories cat_update[] and name inputs which are for new categories cat_insert[]. When you process the form data with PHP you have three arrays:
$ids = $_POST['id']; // Ids for update
$update = $_POST['cat_update']; // Values for UPDATE
$insert = $_POST['cat_insert']; // Values for INSERT
for($i = 0; $i < count($ids); $i++) {
//Execute 'UPDATE `table` SET `value` = $update[$i] WHERE `id` = $ids[$i]
}
for($i = 0; $i < count($insert); $i++) {
//Execute 'INSERT INTO `table` (`value`) VALUES ($insert[$i])
}
I'm not sure I get it, but you could simply give different names to the two sets of categories.
In your second loop putting 'name = "new_cat[]"' will allow you to distinguish between modified categories ('$_POST[cat]') and new ones to be inserted ('$_POST[new_cat]') in your receiving storecats.php code.
Hi all
Now is 2 week that i searching for an answer to my problem and no luck. hope somone can help me on this
i have a chackbox option that i call from the database
<form style="margin-top:-30px" method="POST" action="extradata.php">
<?php
$sql = "SELECT ext_id,ext_price,ext_name,ext_description FROM tbl_extra ORDER by ext_id ASC";
$result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR);
$number = mysql_num_rows($result);
$i = 0;
while ($number > $i) {
$NA= mysql_result($result,$i,"ext_name");
$PR= mysql_result($result,$i,"ext_price");
print "<input type='checkbox' name='extra[]' value='$NA'></td>";
$i++;
}
?>
What i trying to do is to pass the value to extradata.php with 2 value
1.$NA,
2.$PR
when selected box then insert to the database the value of $NA to ex_tra and $PR to ex_price
the extradata.php
<?php
require_once 'library/config.php';
$id=$_POST['pd_id'];
$ssid=$_POST['ct_session_id'];
$total=$_POST['tot'];
$name=$_POST['basedes'];
$qty=$_POST['ct_qty'];
$extra_array = $_POST['extra'];
if ( $extra_array > "0" ) {
foreach ($extra_array as $one_extra) {
$source .= $one_extra.", "; }
$extra = substr($source, 0, -2);
} else {}
$result=mysql_query("INSERT INTO tbl_cart (pd_id, ct_qty, ct_session_id, ex_tra, ex_tra2, ex_price, ct_date) VALUES ('$id','$qty','$ssid','$extra','$name','$total', NOW())");
?>
Best regard to all
Sending two values in one variable is bound to get messy. I would just send the id and get the corresponding values from the database again in extradata.php.
If you really want to send multiple values, I would use fixed indices for the checkboxes (not extra[] but extra[SOME_NUMBER] and add a hidden field next to it (extra_pr[SOME_NUMBER]?) to pass the second value.
Note that you have to use fixed indices as unchecked checkboxes donĀ“t get posted but all hidden fields will get posted.