Sum Values From Different Columns - php

I am having problem adding up the values in a column with php.
These values where sent from checkboxes and i want to count only the values that where checked from the unit column.
Here is my code:
<?php
$id = $_POST['course'];
foreach($id as $value)
{
//echo $value;
$query = " SELECT * FROM french WHERE id= $value ";
$result = mysql_query($query) or die('Error, query failed');
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$course = htmlspecialchars($row['course_name']);
$code = htmlspecialchars($row['course_code']);
$unit = $row['unit'];
$status = $row['status'];
?>

Are you trying like this? Getting form array of form checkboxs and checking on database via ID's?
HTML FORM
Check 1 <input type="checkbox" name="val[]" />
Check 2 <input type="checkbox" name="val[]" />
PHP RESULT
$val = $_POST['val'];
$count = count($val);
foreach ($val as $val_res)
{
$query = 'SELECT * FROM french WHERE id='.$val_res;
}

Related

Duplicate checkbox remove in php

I have two tables named bookings and packages. Checked checkboxes are retrieved from bookings table and are working perfectly. But I also need unchecked check boxes from packages table. The problem is checked checkbox values display again.
<?php
$get_pro = "select * from booking";
$result = mysqli_query($con, $get_pro);
$book_packages = $row_pro['Book_Packages'];
$book_packages = substr(trim($book_packages) , 0, -1);
$split_pkg = (explode(",", $book_packages));
if (!empty($split_pkg)) {
foreach ($split_pkg as $book_pkg) {
$checked = (in_array($book_pkg, $split_pkg)) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="pkg_list_name[]" value="<?php echo $book_pkg; ?>" size="17" <?php echo $checked; ?>> <?php echo $book_pkg; ?> <br>
<?php
}
}
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
if ($package_name != $split_pkg) {
echo "<input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' id='checkbox1' name='pkg_list_name[]'>
<label>$package_name</label><br> ";
} else {
}
}
?>
You shouldn't have two loops. You should only create the checkboxes from the package table. When you're creating those checkboxes, add checked="checked" if the package name is in $split_pkg.
$book_packages = trim($row_pro['Book_Packages']);
$split_pkg = array_map('trim', explode(',', $book_packages));
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
$checked = (in_array($package_name, $split_pkg)) ? 'checked="checked"' : '';
echo "<label><input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' name='pkg_list_name[]' $checked>
$package_name</label><br> ";
}
BTW, it's not a good idea to to put comma-separated values in database columns. You should have a separate row for each booking. Then you would be able to join the two tables easily.

PHP - How to update multiple row using foreach?

so i'm making a php file that updates multiple rows to mysql but I'm having a problem whenever i submit,and I have no idea if I'm using foreach well. here is my code:
$query = "SELECT id, departments, deptName, headOfOffice FROM aip";
$result = mysqli_query($db,$query);
$count = mysqli_num_rows($result);
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>';
echo '<td><input type="text" name="id[]" value="'.$row['id'].'" readonly></td>';
echo '<td><input type="text" id ="department_code" name="department_code[]" value="'.$row['departments'].'"></td>';
echo '<td><input type="text" id="department_name" name="department_name[]" value="'.$row['deptName'].'"></td>';
echo '<td><input type="text" id="department_head" name="department_head[]" value="'.$row['headOfOffice'].'"></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td></td>';
echo '<td></td>';
echo '<td><input type="submit" name="update" value="Update">';
echo '</tr>';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$deptid = $_POST['id'];
$code = $_POST['department_code'];
$dname = $_POST['department_name'];
$dhead =$_POST['department_head'];
foreach($_POST['id'] as $count){ \\ i don't know if this is right.
$query2 = "UPDATE aip SET deparments = '".$code[$count].'" WHERE id = "'.$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}
}
the error says "Undefined offset: 2"
I'm a newbie here, and this is my first time using arrays. hope someone could help. please!
foreach($_POST['id'] as $count => $id){
$query2 = "UPDATE aip SET deparments = '".$code[$count]."' WHERE id = '".$deptid[$count]."'";
$result2 = mysqli_query($db,$query2);
}
P.S. your code is vulnerable to SQL injection
There are two ways of using foreach:
foreach($array as $key => $value){
...
}
or
foreach($array as $value){
...
}
The foreach loop will then iterate through all elements in array, executing the code in brackets for each element once, holding the key name and the value of the element in $key and $value respectively (you can use other than $value and $key as well).
I don't fully understand what exactly you are doing in your code, so if you add an explanation, I will be able to solve your particular case;
i have changed in your script..pls used my script. you do not need to changes any thing just copy and paste my script.
if($_SERVER["REQUEST_METHOD"] == "POST"){
$data = $_POST;
if(count($data['id'])>0){
foreach($data as $key=>$item){
$query2 = "UPDATE aip SET deparments = '".$item['department_code'][$key]."', deptName = '".$item['department_name'][$key]."',headOfOffice = '".$item['department_head'][$key]."' WHERE id = '".$item['id'][$key]."'";
$result2 = mysqli_query($db,$query2);
}
}
}

How to insert multiple rows by select or checkbox

I've got a problem with inserting multiple row to one table.
I've got a 3 tables:
1. student with id_student
2. ankieta with id_ankieta
3. student_ankieta with id_student and id_ankieta
I want to choose students from database using select or checkbox and choose one id_ankieta. After confirming, there are rows created in table (student_ankieta).
Now I can choose students but when I confirm, only one student gets added to the database.
Can anyone help me corect the code?
<?php
echo'<form method="post" action="student_ankieta.php">
<div class="box" style="margin:0 auto; top:0px;">
<h1>Student - ankieta:</h1>
<label>
<span><br/>Ankieta:</span>
</label>
<select class="wpis" name="id_ankieta">
<option>wybierz ankiete</option>';
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['id_ankieta'].'">' . $row{'rok_akademicki'}.' '. $row{'semestr_akademicki'}.' '.$row{'active_ankieta'} .'</option>';
}
echo '
</select>';
$query = "SELECT * FROM student";
$result = mysql_query($query);
echo'
<label>
<span><br/>Wybierz stundentów:</span>
</label>
<select multiple="multiple" name="id_student[]" size="10">';
while ($row = mysql_fetch_assoc($result))
{
echo '<option class="wpis" value="'.$row['id_student'].'" />'.$row{'pesel'}.' '. $row{'nazwisko'}.' '.$row{'imie'} .'</option>';
}
echo'<br/><input class="button" type="submit" value="Dodaj ankiete" name="dodaja">';
if(isset($_POST['dodaja']))
{
$id_ankieta = $_POST['id_ankieta'];
if(empty($_POST['id_ankieta']))
{
echo '<p style="margin-top:10px; font-size:75%; font-family: Calibri; color: red; text-align:center;">Musisz wypełnić wszystkie pola.</p>';
}
else
{
$id_student = $_POST['id_student'];
for ($i = 0; $i < count($id_student); $i++)
{
$id_student = $id_student[$i];
mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('" . $id_student . "','$id_ankieta')");
}
}
}
echo'</div></form>';?>
Put all students in to an array with the key = id_student
$query = "SELECT * FROM ankieta";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
students[$row['id_student']] = array($row['pesel'],$row['nazwisko'],$row['imie'];
}
If the form was posted the confirm will = 1 (from hidden input)
When first enter script "confirm will = 0
When zero, display all student with a check box with a name which includes the id_student in the format of n-i_student.
if intval($_POST['confirm']) = 0){
echo '<form action = "confirm.php" method="post"><input type="hidden" name="confirm" value="1"/><table>';
foreach ($students as $id => val){
echo "<tr><td><input type=\"checkbox\" name=\"n-$id\" value=\"1\" /> Select </div></td>$val[0]<td>$val[0]</td><td>$val[1]</td><td>$val[2]</td></tr>";
}
echo '</table></form>';
}
When confirm = 1
The checkboxes that were checked are inserted.
Check each post value for a key the starts with "n-"
get the rest of the key value after the n- for the id_student value.
Still 1 Major Problem, I do not know where to get the $id_ankieta'
And match it with the id_student.
I left that value as $val[???]
elseif intval($_POST['confirm']) = 1){
foreach ($_POST as $k =>$val){
if (inval($val) == 1 && substr($k,0,2) == 'n-'){
$id = substr($k,2);
$sql = mysql_query("INSERT INTO student_ankieta (id_student, id_ankieta) VALUES ('$id','" . $students[$id][$val[???]] . "')");
}
}
}

Displaying a MySQL Record

I have a form on a page that posts a record id to a page I want to display that record on. The form is:
<form method="post" action="update.php">
<input type="hidden" name="sel_record" value="$id">
<input type="submit" name="update" value="Update this Order">
</form>
I have tested to see if $id is getting the correct value and it does. When it post to update.php it does not return any values. Any ideas? here is the update page code:
$sel_record = $_POST['sel_record'];
$result = mysql_query("SELECT * FROM `order` WHERE `id` = '$sel_record'") or die (mysql_error());
if (!$result) {
print "Something has gone wrong!";
} else {
while ($record = mysql_fetch_array($result)) {
$id = $record['id'];
$firstName = $record['firstName'];
$lastName = $record['lastName'];
$division = $record['division'];
$phone = $record['phone'];
$email = $record['email'];
$itemType = $record['itemType'];
$job = $record['jobDescription'];
$uploads = $record['file'];
$dateNeeded = $record['dateNeeded'];
$quantity = $record['quantity'];
$orderNumber = $record['orderNumber'];
}
}
you have not put the php tags <?php ?> inside the html
<input type="hidden" name="sel_record" value="<?php echo $id; ?>">
You should also try to define those variables outside of the while loop.
$id = '';
$result = mysql_query("SELECT * FROM `order` WHERE `id` = '$sel_record'") or die (mysql_error());
if (!$result) {
print "Something has gone wrong!";
} else {
while ($record = mysql_fetch_array($result)) {
$id = $record['id'];
}
}
Not a full example, but you get the idea.
You have to escape the string... and you can drop the single quotes around order and id.
Try:
$result = mysql_query("SELECT * FROM order WHERE id = '" . $sel_record . "'")
if $sel_record is a String, otherwise remove the single quotes:
...WHERE id = " . $sel_record)
You can also use functions sprintf and mysql_real_escape_string to format:
$query = sprintf("SELECT * FROM order WHERE id = '%s'",
mysql_real_escape_string($sel_record));

How can I make better design about understanding which checkbox is checked in order to put its value to mysql?

I have 2 checkboxes. Their values go to another php file and if any of them is checked, its value is inserted mysql codes. I did it, but when the number of checkbox increase and more advanced things appear, my code will be impossible to put into practise.
Here is checkbox.php :(it is inside a form)
<div>
<label>Choose:</label>
<label>Camera </label><input type="checkbox" name="kind[]" value="1" />
<label>Video </label><input type="checkbox" name="kind[]" value="2"/>
</div>
when the form is clicked, it goes to fetch_kind.php via AJAX and jquery($.post).
Here is code:
<?php
$kind = array();
$kind = $_POST['kind'];
$count = count($kind);
if ($count== 0) {
echo "You did not checked any of checkboxes!!!";
}
if ($count == 2) {
$sql = "SELECT id,kind FROM products";
} else {
foreach ($kind as $value) {
if ($value =="1") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
if ($value =="2") {
$sql = "SELECT id,kind FROM products WHERE kind = " . $value;
}
}
}
?>
Could you give a better example? Thank you...
A simple way would be to group all the values and us IN
if ($count > 0){
$sql = "SELECT id,kind FROM products WHERE kind IN (" . implode (',', $kind) . ")";
}
Also you might want to look into sanitizing you input.
You can loop through all your checkboxes and add a simple condition to an array. You implode the array at the end.
Something like:
$conds = array();
foreach ($kind as $value) {
$conds[] = '`kind` = ' . intval($value);
}
$sql = "SELECT id,kind FROM products WHERE " . implode(" OR ", $conds);

Categories