Ive new in php and Im learning now how to retrive data from sql. Ive faced some issue that I couldnt find any answer for it over the web.
I would like to make an html form with many check boxes (as many as my data base supplies) and to every check box i would like to assign an associative array that contains all of the row data from the db. for example if I have in my db columns names 'first name','last name' and 'age' the check box value will be ['first name'=>'xx', 'last name'=>'yy', age'14'];
so far Ive only manage to pass it as as string like this:
value="<?php echo implode(array('key'=>$row['first name'], 'name'=>$row['last name'],'type'=>$row['age']));?>"/>
but when I pass it with post method I get regular String that I cant format to an array again.. this is my form code :
function deleteRow(){
global $conn;
if(!$conn){
die("connection failed: ".mysqli_connect_error());
}else{
$query = "SELECT * FROM salary.collage ";
$result=mysqli_query($conn, $query);
echo "<table border='1'>";
echo "<form method='post' id='form_delete_rows' action='test.php'";
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><input type="checkbox" name="key[]" value="<?php echo implode(array('key'=>$row['key'], 'name'=>$row['name'],'type'=>$row['type']));?>"/></td>
<td><?php echo $row['key']?></td>
<td><?php echo $row['name']?></td>
<td><?php echo $row['type']?></td>
</tr>
<?php
}
echo"<input type='submit' name='deleteRows' value='delete selected rows'/>";
echo "</form>";
echo "</table>";
and this is the function that handles the retrieved data:
if(!empty($_POST["deleteRows"])){
if(isset($_POST["key"])){
var_dump($_POST["key"]);
echo "are you sure you want to delete these records?<br/>";
echo "<pre><table border='1'>";
foreach ($_POST['key'] as $select=>$value) {
echo "<tr>";
echo "<td>{$select}</td>";
echo "<td>{$value}</td>";
echo "</tr>";
}
}echo "</table></pre>";
}
if database tabe has a unique key eg index the use it like:
name="delete[]" value="<?php echo $row['indexname'];?>"
for the checkbox and do foreach $row field as $k => $v int the same td:
<input type="hidden" name="key[<?=$row['indexname'];?>][<?php echo $k;?>]" value="<?php echo $v;?>"/>
but index with spaces wont work , in delete you can find the selected index eg ids wg keys whatever
if u want to see it do make a little table for each $row within in the < td> horizontal or vertical
tr th $k /th td $v/td /tr
You're calling implode()
without ever specifying a "glue" characters, so
$foo = array('a','b',c');
echo implode($foo);
will give you
abc
Just specify a glue char:
echo implode($foo, '|');
-> a|b|c
but overall, don't do this. You're simply assuming that the text in your array will not contain the separator character. If this text is just being passed through your form, you should use a better encapsulation method, e.g. json_encode()
, which won't suffer from "injection attack" problems.