Check checkboxes if value is present in a database - php

I have a form that allows the user to add or remove users from a job by using checkboxes. At the moment the engineer's names etc are stored in a table called 'users' and they are identified by their user type, engineers. The checkboxes on the form are created by using a while loop to display a mysql query. This is done so that new users can be added to the database via a webpage at a later date and their name will automatically be added to the list of available engineers. To add an engineer to a job their name is simply ticked and the form submitted.
This works well but I would like the user to be able to add or remove users by checking and unchecking boxes on another form but I can't think for the life of me how to do this.
The users assigned to a job are stored in a many-to-many table called calls_engineers which has 3 fields
id_ce (unique id)
call_ce (id of job, a foreign key)
engineer_ce (id of engineer, a foreign key)
The engineer_ce is the users primary key in the 'users' table which is 'id'.
The code I have so far is...
<? $sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id'";
$result = mysql_query($sql) or die(mysql_error());
$row2 = mysql_fetch_array($result);
$sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){ ?>
<div style="width:70px; float:left">
<?
if($row2['engineer_ce'] == $row['id']){
?>
<input type="checkbox" name="engineer[]" checked="checked" value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name'];
} else { ?>
<input type="checkbox" name="engineer[]" value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name'];
}?>
</div>
<?
}
?>
All this does is create checkboxes for each user which is an engineer but it doesn't check them if the user is assigned to the job.
Any help will be greatly appreciated

You never loops the calls_engineers table. Using
$row2 = mysql_fetch_array($result);
Will not actually find all assignments for the engineer. Now check every single engineer if this is included in current job:
<?
$sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){ ?>
<div style="width:70px; float:left">
<input type="checkbox" name="engineer[]" <?
$result2 = mysql_query("SELECT * FROM calls_engineers WHERE call_ce = '".mysql_real_escape_string($diary_id)."' AND engineer_ce = ".$row['id']);
if(mysql_num_rows($result2) > 0) echo 'checked="checked"';
?> value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name']; ?>
</div>
<? } ?>

Related

insert multiple rows data into database fetched from another table

i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert

php modify database from html table select by checkbox

Good morning everybody
I made a table in html that contains users and the select box contains profiles.
I want to assign every users profile in database according to the profile selected in html.
My table in html contains checkbox next to every user. I want every user that is checked to be assigned.
<form action="PHP/modifier.php" method="POSt">
<table>
<thead>
<tr>
<th><input type="checkbox" id="checker" name="all"></th>
<th>Username</th>
<th>Nom</th>
<th>Prenom</th>
</tr>
</thead>
<?php
$query="SELECT Username,Nom,Prenom from user";
$result = mysql_query($query);
$num = mysql_num_rows($result);
for ($i = 0; $i < $num; $i++){
$row =mysql_fetch_array($result);
$Username = $row['Username'];
$Nom = $row['Nom'];
$Prenom = $row['Prenom'];
echo "<tr id='row'>";
echo "<td><input type='checkbox' id='check' name='check'".$Username."></td>";
echo"<td>".$Username."</td>";
echo "<td>".$Nom."</td>";
echo "<td>".$Prenom."</td>";
echo "<td><div id='MAJ'>";
echo "</div></td>";
echo "</tr>";
}
?>
<h2>Selectionner l'utilisateur et le profile</h2>
<select name="profile" id="profilez" required>
<option>Injecteur</option>
<option>Utilisateur</option>
<option>Administrateur</option>
<option>Utilisateur superieur</option>
<input type="submit" value="Associer">
</form>
In the modifer.php
I want to make update function to update users but how to get information from checked cases in the html table?
I already wrote this
<?php
include "functions.php";
$profile=$_POST['profile'];
$Username=$_POST['Username'];
$query="UPDATE user SET profile = '$profile' WHERE Username = '$Username' " ;
?>
I don't know how to do it.
thank you so much and sorry for my bad english.
there are different ways to do it. but lets go with your way
on you modifer.php page make another query to get all user names
$row =mysql_fetch_array($result);
foreach ($row as $value)
{
if (isset($_POST['check'.$value['username']]))
{
$profile = $_POST['profile'];
$Username = $POST['check'.$value['username'];
$query="UPDATE user SET profile = '$profile' WHERE Username = $value['username'] " ;
}
}

How to delete random row using button in PHP?

<?php
include("connection.php");
echo "Do you really want to DELETE this field? " ;
?>
<form method="post">
<input type="submit" name="yes" value="YES" />
<?php
$res = mysql_query("SELECT * FROM members");
while($row = mysql_fetch_array($res))
{
if(isset($_REQUEST['yes']))
{
$id=$row['id'];
echo $id;
mysql_query("DELETE from members WHERE id= '$id' ");
header("location: view.php");
}
}
?>
<input type="submit" name="no" value="NO" />
<?php
if(isset($_REQUEST['no']))
{
header("location: view.php");
}
?>
</form>
</body>
This is my code for delet random row from list view when click on delete button but i m not getting the result so please help me out of these.
Pass db connection as second parameter to your mysql_query() to delete rows from members table:
mysql_query("DELETE from members WHERE id= '$id'" , $dbCon);
Here DB connection I mean something this that you have defined in your connection.php file:
$db_host="localhost";
$db_name="test";
$username="root";
$password="";
$dbCon=mysql_connect($db_host,$username,$password);
I hope this solve your problem!
Change this line:
mysql_query("DELETE from members WHERE id= '$id' ");
to that:
mysql_query("DELETE FROM members WHERE id= '".$id."' ");
Your query SELECT * FROM members without ordering will select all the lines in a unpredictable order.
The ifs in your while loop will be either always true or always false:
if the user click on the YES button, all the rows of the table will be deleted as you don't have exit; after the header("location: view.php"); (see this post)
if the user click the NO button, then every iteration of the while loop won't do nothing.
So what you should do:
Have an hidden parameter in your form containing the id of the field you want to delete.
Test when the user submit the form that the hidden field is present and sanitized.
Do not select all the rows of the table
Delete the rows secificaly by its primary key.
Call exit; after header("location: view.php");
When do an if inside a loop, move it outside the loop if possible if the values do not change.
<?php
include("connection.php");
echo "Do you really want to DELETE this field? " ;
?>
<form method="post">
<input type="submit" name="yes" value="YES" />
<?php
if(isset($_REQUEST['yes']))
{
if(isset($_GET['delet']))
{
$id = $_GET['delet'];
$res = mysql_query("SELECT * FROM members WHERE id = '$id' ");
$row = mysql_fetch_array($res);
$did = $row['id'];
$dname = $row['name'];
$dphn = $row['phn'];
/*echo $did;
echo $dname;
echo $dphn;*/
$ins = "INSERT INTO del (mid,name,phn) values ('$did','$dname','$dphn')";
mysql_query($ins);
mysql_query("DELETE FROM members WHERE id = '$id' ");
header('location: view.php');
}
}
?>
<input type="submit" name="no" value="NO" />
<?php
if(isset($_REQUEST['no']))
{
header("location: view.php");
exit;
}
?>
</form>

How to read/send post data with php and hold a variable in it

I have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.

PHP showing stored checkbox data to an update form

I was wondering if anyone could help, I am creating an update product form which is showing results of data already in the database. I want to display all the checkbox categories and have the ones that have already been selected as checked so the user can easily select and change.
I know I am overcomplicating the code below but I am really no sure how to go about this. The code below currently selects all the categories and displays them as checkboxes but I cant get it to display the ones the user has already selected and saved to the db as checked. Also I am using MySQL original version not the improved one which I know I should be but If anyone could help I would really appreciate it Thanks Louise.
<?php
$query = "SELECT * FROM category, catid_productid WHERE catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$result = mysql_query($query);
$query = "SELECT * FROM category, catid_productid WHERE category.cat_id = catid_productid.cat_id AND catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$selected_result = mysql_query($query);
$selected_array = array($selected_result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id;
if (isset($_GET['product_id']) && in_array($selected_array['$selected_result'], $selected_array)) {
echo 'checked="checked"';
}
echo " /></li>'";
}
?>
form field:
<div class="field-row ">
<label for="categories"> Categories:<?php
if (isset($required) && in_array('category', $required)) { ?>
<span class="warning">*</span><?php } ?></label>
<div class="fields">
<ul>
<?php
$query = "SELECT * FROM category ORDER BY title ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id.'" /></li>';
}
?>
</ul>
</div>
</div>
inserting it into the database
if($result) {
$product_id = mysql_insert_id();
foreach ($category as $cat_id)
{
// connect to mysql database
mysql_query("INSERT INTO catid_productid (cat_id, product_id) VALUES ('$cat_id', '$product_id')");
}
I don't know if you store checked-or-not information in your DB but I do spot mis-quotation here ..
Try changing this
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id;
To
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id.'"';
AND this
echo " /></li>'";
to
echo ' /></li>';

Categories