Updating multiple rows in mysql with checkboxes? - php

I'm using checkbox buttons for updating occupation of day in month in my calendar.
If I check just one checkbox it updates it, but if I check multiple checkboxes it doesn't update any row.
Here is my code:
$query = mysqli_query($con, "SELECT * FROM koledar");
while ($vsidnevi = mysqli_fetch_assoc($query)) {
$dnevi = [$vsidnevi['dan']];
foreach ($dnevi as $dan) {
if ($vsidnevi['zasedenost']==0) {
echo '<label class="btn btn-primary">';
echo '<input type="checkbox" name="miha" value="' . $dan . '" data-toggle="button">' . $dan;
echo '</label>';
} elseif ($vsidnevi['zasedenost']==1) {
echo '<label class="btn btn-primary active disabled">';
echo '<input type="checkbox" name="miha" value="' . $dan . '" data-toggle="button">' . $dan;
echo '</label>';
}
}
}
and
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$daen = $_POST['miha'];
$dodaj = mysqli_query($con, "UPDATE koledar SET zasedenost=1 WHERE dan=" . $daen . "");
}
}

Firstly, you should be passing your literal values to MySQL as parameters to a prepared statement (in order to defeat SQL injection attacks).
When multiple values are submitted, $_POST['miha'] will be an array over which you must loop:
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$dodaj = mysqli_prepare($con, '
UPDATE koledar
SET zasedenost=1
WHERE dan=?
');
mysqli_stmt_bind_param($dodaj, 's', $daen);
foreach ($_POST['miha'] as $daen) {
mysqli_stmt_execute($dodaj);
}
}
}
Or else use IN ():
if (isset($_GET['dodaj']) && $_GET['dodaj']=="true") {
if(isset($_POST['miha'])) {
$inq = implode(',', array_fill(0, count($_POST['miha']), '?'));
$dodaj = mysqli_prepare($con, "
UPDATE koledar
SET zasedenost=1
WHERE dan IN ($inq)
");
call_user_func_array('mysqli_stmt_bind_param', array_merge(
array(
$dodaj,
str_repeat('s', count($_POST['miha']))
),
$_POST['miha']
));
mysqli_stmt_execute($dodaj);
}
}

Related

Create Checkbox for every Row in the Table with PHP and HTML. How can i call them in the PHP Section?

EDIT: Here is the SQL SELECT
$statement = $db->prepare("
SELECT A.Vorname
, A.Nachname
, O.IndexcardRight
, O.QuizRight
, O.Admin_AdminID
FROM Admin A
LEFT
JOIN AdminOfModule O
ON O.Admin_AdminID = A.AdminID
WHERE O.AdminTyp = 'Student'
GROUP
BY A.AdminID
");
$statement->execute();
$admin = $statement->fetchAll(PDO::FETCH_ASSOC);
$count = $statement->rowCount();
Here is the PHP and HTML Code with the Update SQL
which doenst work for sure because i have no unique id's
i tried some stuff like give in the name or id quiz[] but i cannot call it in the php function. And couldnt find much ways to do it.
<form method="post">
<?php
$i = 2;
$y = 2;
foreach ($admin as $row) {
$aii = $row['Admin_AdminID'];
$i++;
$y++;
echo '<label>' . $row["Vorname"] . $row["Nachname"] . '</label>';
echo '<br>';
echo '<label> Quiz</label>';
//echo'<input type="hidden>"';
echo '<input type="checkbox" name="quiz' . $i . '" id="quiz' . $i . '"> ';
echo '';
echo '<label> Indexcard</label>';
echo '<input type="checkbox" name="indexcard' . $i . '" id="indexcard' . $i . '">';
echo '<br>';
//quizx indexcardx wenn button geklickt und wenn quizx isset dann update table adminofmodule set quizright =1 where
}
if (isset($_POST['submit'])) {
//$ic = $_POST["indexcard$i"];
//$q = $_POST["quiz$i"];
if (isset($_POST["quiz$i"])) {
$stmt = $db->prepare("UPDATE AdminOfModule SET QuizRight = 1 WHERE '$aii' = '$i' ");
$stmt->execute();
}
else {
$stmt1 = $db->prepare("UPDATE AdminOfModule SET QuizRight = 0 WHERE '$aii' = '$i' ");
$stmt1->execute();
}
if (isset($_POST["indexcard$i"])) {
$stmt2 = $db->prepare("UPDATE AdminOfModule SET IndexcardRight = 1 WHERE'$aii' = '$i'");
$stmt2->execute();
}
else {
$stmt3 = $db->prepare("UPDATE AdminOfModule SET IndexcardRight = 0 WHERE'$aii' = '$i' ");
$stmt3->execute();
}
}
echo '<input type="submit" name="submit" id="submit">';
?>
</form>
The Problem is, if i check the Checkbox at the first rows it will stand 0 but if click the last Checkbox it sets all to 1.

Trying to insert into a database as well as post items from a multi select drop-down menu

I need to be able to save selected items from a multi select drop-down list into a MySQL DB and display all the selected items. When I hit submit only the last item is saved.
Code originally was for a single item to be selected from a drop-down menu. I have modified it for selecting multiple items (for ease of editing by other people). I have tried various solutions including if is_array, for loops and foreach loops without any luck. Can anyone point me in the right direction please.
HTML code
<select name="topic_id[]" multiple="multiple" id="select">
<?php
$topic_set = find_all_topics();
while($topic = mysqli_fetch_assoc($topic_set)) {
foreach($topic_set as $topic) {
echo "<option value=\"" . $topic['id'] . "\"";
if($page['topic_id'] == $topic['id']) {
echo " selected";
}
echo ">" . $topic['menu_name'] . "</option>";
}
}
mysqli_free_result();
?>
</select>
PHP
function insert_page($page) {
global $db;
$errors = validate_page($page);
if(!empty($errors)) {
return $errors;
}
shift_page_positions(0, $page['position'], $page['topic_id']);
$post_t_ids = array();
foreach($_POST['topic_id'] as $post_t_id) {
$post_t_ids[] = (int) $post_t_id;
}
$post_t_id_joined = join('), (', $post_t_ids);
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES (";
$sql .= "'" . db_escape($db, $post_t_id_joined) . "',";
$sql .= "'" . db_escape($db, $page['content']) . "'";
$sql .= ")";
$result = mysqli_query($db, $sql);
if($result) {
return true;
} else {
echo mysqli_error($db);
db_disconnect($db);
exit;
}
}
if(is_post_request()) {
$page = [];
$page['topic_id'] = $_POST['topic_id'] ?? '';
$page['content'] = $_POST['content'] ?? '';
$result = insert_page($page);
if(!isset($_POST['topic_id'])) {
$_POST['topic_id'] = [];
}
if($result === true) {
$new_id = mysqli_insert_id($db);
} else {
$errors = $result;
}
}
The result should be selecting multiple items from the drop-down list and upon clicking submit all selected items should save to the DB and displayed to a different page. No error messages pop up but only the last item selected gets saved and displayed.
Your part to make an sql statement is wrong. It will produce you something like:
INSERT INTO pages (topic_id, content) VALUES ('1), (2), (3','content')
You need to modify your code to get a proper sql statement. Of course, I would recommend you to use prepared statements:
$params['content'] = $page['content'];
$stmt = $mysqli->prepare('INSERT INTO pages (topic_id, content) VALUES (:id, :content)');
foreach($_POST['topic_id'] as $id) {
$params['id'] = $id;
$stmt->execute($params);
}
If you still want to use your approach, you should do it like this:
$content = $page['content'];
$makeValues = function($id) use ($content) {
return "($id, '$content')";
};
$post_t_id_joined = implode(', ', array_map($makeValues, $post_t_ids));
$sql = "INSERT INTO pages ";
$sql .= "(topic_id, content) ";
$sql .= "VALUES $post_t_id_joined";

Why is MySQL INSERT statement not working without error

A php/mySQL booking function that's been working well suddenly stopped inserting booking entries into the database, with no changes to the code and a functioning database connection.
I run a parallel version of the page that is working on another website; the only difference between the two is that the broken version is running on php 5.6, the functioning one is still on 5.4.
Adding an error log brings no results even though the table doesn't update and I can't see any deprecated statements between php 5.4 and 5.6.
Can anyone spot the problem I'm missing?
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach ($_POST['class_id'] as $classes) {
$class_id = (int)$classes;
//UPDATE the bookings table **THIS PART IS NOT WORKING**:
$query = "INSERT INTO bookings (user_id, booking_name, class_id, time_stamp) VALUES ('$user_id', '$username', '$class_id', NOW())";
mysqli_query($dbc, $query);
}
foreach($_POST['class_id'] as $classes){
$class_id = (int)$classes;
//Change the booking numbers **THIS WORKS FINE**:
$increase = "UPDATE classes SET online_bookings = (online_bookings + 1), total_bookings = (total_bookings + 1), free_spaces = (free_spaces - 1) WHERE class_id = $class_id";
mysqli_query($dbc, $increase);
}
mysqli_close($dbc);
..and the table that provides the $_POST data:
echo'<div class="container">';
echo'<div class="span8 offset1 well">';
echo'<p class="lead text-info">Do you want to reserve space at these classes?</p>';
//table header
echo '<table id="dancers" class="table table-bordered table-hover">';
echo '<thead><tr><th>Date</th><th>Time</th><th>Venue</th><th>Who\'s going?</th></tr></thead>';
//create the form
echo '<form id="makebkg" method="post" action="' . $_SERVER['PHP_SELF'] . '">';
//Get the class IDs from the GET to use in the POST
foreach ($_GET['sesh'] as $class_id) {
$sql = "SELECT class_id, DATE_FORMAT(date, '%a, %d %b') AS new_date, DATE_FORMAT(time, '%H:%i') AS new_time, venue FROM classes WHERE class_id = '$class_id'";
$data = mysqli_query($dbc, $sql);
//get table data
while ($row = mysqli_fetch_array($data)) {
$date = $row["new_date"];
$time = $row["new_time"];
$venue = $row["venue"];
$class_id = $row["class_id"];
}
//Show a table of the selected classes
echo '<tr><td>' . $date . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $venue . '</td>';
echo '<td>' . $username . '</td></tr>';
echo '<input type="hidden" name="date[]" value="' . $date . '" />';
echo '<input type="hidden" name="time[]" value="' . $time . '" />';
echo '<input type="hidden" name="venue[]" value="' . $venue. '" />';
echo '<input type="hidden" name="username[]" value="' . $username . '" />';
echo '<input type="hidden" name="class_id[]" value="' . $class_id . '" />';
}
echo'</table>';
//Go Back button
echo '<a class="btn btn-link pull-left" href="classes.php"><i class="icon-arrow-left"></i> Go back</a>';
// Make booking button - LIVE
echo'<div id="confirmbtn">';
echo '<input type="submit" id="confirm" name="submit" class="btn btn-large btn-primary pull-right" value="Confirm">';
echo '</div>';
OK, I finally fixed the problem.
It turns out that the hosting company had changed the MySQL mode to 'strict'.
The INSERT statement here left some table columns blank and strict mode rejects the entire insert as a result. Changing the mode right before the insert command was a quicker way to get around the problem than updating the insert command:
// TURN OFF STRICT MYSQL MODE
$strict = "SET sql_mode = ''";
mysqli_query($dbc, $strict);
Thanks for all the advice and tolerance of an indolent coder.
Did you try to check your query?
error_reporting(1);
$q = mysqli_query($dbc, $query);
if (!$q)
{
echo 'Error' . mysqli_error($dbc);
}
Do same for other query.

Combine multiple POSTs and adding it to table

Here is my code to add multiple types to table. I want to combine areas, location, types and add them in the table at once. I think this just wont work if(!empty($_POST['types'] && $_POST[''] && $_POST[''] ) Thanks!
if(!empty($_POST['types'])) {
$values = array();
foreach($_POST['types'] as $typ_id) {
$values[] = sprintf('(%d, %d)', $station_id, $typ_id);
}
$query = 'INSERT IGNORE INTO station_typ_tab
(station_id, typ_id, area_id, location_id)
VALUES ' .
implode(',', $values);
mysql_query($query, $db) or die(mysql_error($db));
}
EDIT: here is part of code for types[] and same is for areas and location
<td>Types:<br/> <small>CTRL + click to set multiple pollutants</em></small>
</td>
<td>
<?php
$query = 'SELECT typ_id, typ FROM typ_tab ORDER BY typ ASC';
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
echo '<select multiple name="types[]">';
while ($row = mysql_fetch_array($result)) {
if (isset($station_typ[$row['typ_id']])) {
echo '<option value="' . $row['typ_id'] . '"
selected="selected">';
} else {
echo '<option value="' . $row['typ_id'] .'">';
}
echo $row['typ'] . '</option>';
}
echo '</selected>';
} else {
echo '<p><strong>Databaza je prazdna... Enter database</strong></p>';
}
mysql_free_result($result);
how to combine $_POST for types, location and areas if they comes from different selecting input. something like if(!empty($_POST['types'] && $_POST['areas'] && $_POST['location']) ){ $values = array(); foreach( NEW VARIABLE as $typ_id && area_id &&location_id) { $values[] = sprintf('(%d, %d, %d, %d)', $station_id, $typ_id, area_id, location_id); if it is possible to do it like this
to combine in IF try to use
if((!empty($_POST['types'])) && (!empty($_POST['area'])) && (!$_POST['location'])));

How to build a dynamic MySQL INSERT statement with PHP

Hello
This part of a form is showing columns names from mysql table (names of applications installed on a computer) and creating a form with YES/NO option or input type="text" box for additional privileges to a application..
How can I insert it back to a mysql table using POST and mysql_query INSERT INTO?????
Quantity of columns is changing because there is another form for adding applications with/without privileges..
<tr bgcolor=#ddddff>';
//mysql_query for getting columns names
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
//exclude these columns bcs these are in other part of form
if($row[0] == 'id' || $row[0] == 'nameandsurname' || $row[0] == 'department'
|| $row[0] == 'phone' || $row[0] == 'computer' || $row[0] == 'data')
continue;
echo '<td bgcolor=#ddddff>'.$row[0].'<br />';
if (stripos($row[0], "privileges") !== false) {
echo '<td bgcolor=#ddddff><p><a class=hint href=#>
<input type="text" name="'.$row[0].'">
<span>Privileges like "occupation" or "like someone"</span></a></p></td></tr>';
}
else
{
echo '<td bgcolor=#ddddff align=center><select name="'.$row[0].'">
<option value = "No">No
<option value = "Yes">Yes
</td>
</tr>';
}
}
trim($_POST); // ????
$query = "INSERT INTO 'employees' VALUES (??)"; // ????
Because you're not inserting ALL columns, you need to dynamically build an insert statement that will specify the columns you're inserting into.
First, create an array of the columns you want to use. Use this both to generate your form and to retrieve the values
$exclude = array("id", "nameandsurname", "departument", "phone", "computer", "date");
$result = mysql_query("SHOW COLUMNS FROM employees") or die(mysql_error());
$columns = array();
while ($row = mysql_fetch_array($result)) {
if (!in_array($row[0], $exclude) {
$columns[] = $row[0];
}
}
Render your form from the $columns array:
foreach ($columns as $column) {
echo '<tr><td bgcolor="#ddddff">'.$column.'<br />';
if (stripos($column, "privileges") !== false) {
echo '<p><a class="hint" href="#">
<input type="text" name="'.$column.'">
<span>Privileges like "occupation" or "like someone"</span></a>';
} else {
echo '<select name="'.$column.'">
<option value = "No">No
<option value = "Yes">Yes
</select>';
}
echo '</td></tr>';
}
Then, dynamically build your INSERT string from the posted values for those columns. Be sure to protect against SQL injection:
$keys = array();
$values = array();
foreach ($columns as $column) {
$value = trim($_POST[$column]);
$value = mysql_real_escape_string($value);
$keys[] = "`{$column}`";
$values[] = "'{$value}'";
}
$query = "INSERT INTO 'employees' (" . implode(",", $keys) . ")
VALUES (" . implode(",", $values) . ");";
Note: this will work better if you select from INFORMATION_SCHEMA.COLUMNS so that you can know the type of column you're inserting into. That way, you won't have to quote everything.
<html>
<body>
<form action="dynamicinsert.php" method="POST" >
user name:<br>
<input type="text" id="username" name="username">
<br><br>
first name:<br>
<input type="text" id="firstname" name="firstname">
<br><br>
password:<br>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" name="submit" value="add" />
</form>
</body>
</html>
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "you_DB_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function insertqueryfunction($dbfield,$table) {
$count = 0;
$fields = '';
foreach($dbfield as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = addslashes($col);
$val = addslashes($val);
$fields .= "`$col` = '$val'";
}
$query = "INSERT INTO $table SET $fields;";
return $query;
}
if(isset($_POST['submit']))
{
// Report all errors
error_reporting(E_ALL);
// Same as error_reporting(E_ALL);
ini_set("error_reporting", E_ALL);
$username_form = $_POST['username'];
$firstname_form = $_POST['firstname'];
$password_form = $_POST['password'];
$you_table_name = 'you_table_name';
$dbfield = array("username"=>$username_form, "firstname"=>$firstname_form,"password"=>$password_form);
$querytest = insertqueryfunction($dbfield,'you_table_name');
if ($conn->query($querytest) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>

Categories