How can i insert multiple values into database? - php

I'm trying to insert multiple values into my database, the values are from a jQuery script that generate a tags when you click space.
I tried to put a name on the tag, but it only insert into the database, the last tag, i want to insert all tags.
Here my code
<script type='text/javascript'>
$(window).load(function(){
function closer(){
$('#close').live('click', function() {
$(this).parent().remove();
});
}
$('#tags').keypress(function(e) {
if(e.which == 32) {
var tx = $('#tags').val();
if (tx) {
$(this).val('').parent().before('<li class="tags"><span><input type="hidden" value="'+tx+'" name="tags">'+tx+'</input></span><a style="cursor:pointer;" id="close">[x]</a></li>');
closer();
}
}
});
});
</script>
<?php
include(PATH_MODULE . '/joboffers/view/joboffers_view.php');
//add job offer function
function addjo(){
connect();
addjoview();
//check if the button was clicked
if (isset($_POST['add_jo'])){
if ($_POST['job_category']) {
$job_category = mysql_real_escape_string($_POST['job_category']);
$check1 = 0;
} else {
$check1 = 1;
}
if ($_POST['description']) {
$description = mysql_real_escape_string($_POST['description']);
$check2 = 0;
} else {
$check2 = 1;
}
if ($_POST['job_name']) {
$job_name = mysql_real_escape_string($_POST['job_name']);
$check3 = 0;
} else {
$check3 = 1;
}
if ($_POST['hiring_manager']) {
$hiring_manager = mysql_real_escape_string($_POST['hiring_manager']);
$check4 = 0;
} else {
$check4 = 1;
}
if ($_POST['tags']) {
$tags = mysql_real_escape_string($_POST['tags']);
$check5 = 0;
} else {
$check5 = 1;
}
if ($_POST['localization']) {
$localization = mysql_real_escape_string($_POST['localization']);
$check6 = 0;
} else {
$check6 = 1;
}
if ($_POST['attributes']) {
$attributes = mysql_real_escape_string($_POST['attributes']);
$check7 = 0;
} else {
$check7 = 1;
}
if ($_POST['contract_type']) {
$contract_type = mysql_real_escape_string($_POST['contract_type']);
$check8 = 0;
} else {
$check8 = 1;
}
if ($_POST['professional_exp']) {
$professional_exp = mysql_real_escape_string($_POST['professional_exp']);
$check9 = 0;
} else {
$check9 = 1;
}
//verify if all fields are right
if ($check1 == 0 && $check2 == 0 && $check3 == 0 && $check4 == 0 && $check5 == 0 && $check6 == 0 && $check7 == 0 && $check8 == 0 && $check9 == 0){
$query =("INSERT INTO job_offers (job_category, description, job_name, hiring_manager, tags, localization, attributes, contract_type, profissional_experience) VALUES ('" . $job_category . "','" . $description . "','" . $job_name . "','" . $hiring_manager . "','" . $tags . "', '" . $localization . "', '" . $attributes . "', '" . $contract_type . "', '" . $professional_exp . "')");
db_query($query, '+');
echo "Congratulations! You have been successfully registered in our system.";
} else {
echo "Ops, something went wrong!";
}
}
}
?>
HTML
<form method="POST">
<br>
<label>Job category</label>
<input type="text" name="job_category" maxlength="100" >
<br><br>
<label>Description</label>
<textarea cols="22" rows="3" name="description"></textarea>
<br><br>
<label>Job name</label>
<input type="text" name="job_name" maxlength="130" >
<br><br>
<label>Hiring manager</label>
<input type="text" name="hiring_manager" maxlength="130" >
<br><br>
<label>Tags</label>
<div id="wrapbox">
<div id="box">
<input type="text" id="tags" class="tagstype" maxlength="230">
</div>
</div>
<br><br>
<label>Localization</label>
<input type="text" name="localization" maxlength="130" >
<br><br>
<label>Attributes</label>
<input type="text" name="attributes" maxlength="130" >
<br><br>
<label>Contract type</label>
<input type="text" name="contract type" maxlength="130" >
<br><br>
<label>Professional experience</label>
<input type="text" name="professional_exp" maxlength="130" >
<br><br>
<input name="add_jo" type="submit" />
</form>

Try changing this
<input type="hidden" value="'+tx+'" name="tags">
to this
<input type="hidden" value="'+tx+'" name="tags[]">
Then, in your PHP code, do something like this
if ($_POST['tags']) {
$tags = mysql_real_escape_string(implode(",", $_POST['tags']));
$check5 = 0;
} else {
$check5 = 1;
}
That will insert a comma-separated list of the tags into your tags field in your table. If you would rather have it be space-separated, simply use implode(" ", $_POST['tags']) instead.
That being said, I would suggest restructuring your database so that you do not have a tags column in your job_offers table. Instead, you would have a job_offer_tags table which would have the columns id, job_id and tag, and you only enter single tags into the tag column.

Related

How do I get PHP to stop recognizing NULL values as elements in an array? [duplicate]

This question already has answers here:
How to submit data of a form with repeated field names?
(2 answers)
What is the difference between empty() , isset() and is_null() function in php?
(1 answer)
Closed 1 year ago.
This program is supposed to accept scores for 20 assignments, store them in an array, and then echo two things: the number of assignments for which a score was entered, and the total of all the scores. My issue is that no matter whether or not I enter a value for an assignment, php not only echos a label for the assignment, but it counts the empty field as part of the array and adds it to the variable I'm using to store the number of assignments for which a score has been entered. The below is the page on which the user enters their score(s), and the page below that is the page that is supposed to display their results.
<!DOCTYPE html>
<html>
<head>
<title>Assignments</title>
<link href="main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
<h1>Enter Your Scores (0-100, 2000 possible)</h1></br>
<p>Press The "Calculate" button when finished.</p></br>
<form action="arraysolo.php" method="post">
<div id="data">
<label>Assignment 1</label>
<input type="text" name="assign1"><br />
<label>Assignment 2</label>
<input type="text" name="assign2"><br />
<label>Assignment 3</label>
<input type="text" name="assign3"><br />
<label>Assignment 4</label>
<input type="text" name="assign4"><br />
<label>Assignment 5</label>
<input type="text" name="assign5"><br />
<label>Assignment 6</label>
<input type="text" name="assign6"><br />
<label>Assignment 7</label>
<input type="text" name="assign7"><br />
<label>Assignment 8</label>
<input type="text" name="assign8"><br />
<label>Assignment 9</label>
<input type="text" name="assign9"><br />
<label>Assignment 10</label>
<input type="text" name="assign10"><br />
<label>Assignment 11</label>
<input type="text" name="assign11"><br />
<label>Assignment 12</label>
<input type="text" name="assign12"><br />
<label>Assignment 13</label>
<input type="text" name="assign13"><br />
<label>Assignment 14</label>
<input type="text" name="assign14"><br />
<label>Assignment 15</label>
<input type="text" name="assign15"><br />
<label>Assignment 16</label>
<input type="text" name="assign16"><br />
<label>Assignment 17</label>
<input type="text" name="assign17"><br />
<label>Assignment 18</label>
<input type="text" name="assign18"><br />
<label>Assignment 19</label>
<input type="text" name="assign19"><br />
<label>Assignment 20</label>
<input type="text" name="assign20"><br />
</div>
<div id="button">
<label>&nbsp </label>
<input type="submit" value="Calculate" /><br />
</div>
</form>
</div>
</body>
</html>
The below is the page which displays the users results.
<!DOCTYPE html>
<html>
<head>
<title>Your Results:</title>
<link href="main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
<h1>Score Per Assignment:</h1></br>
<?php
$score = array();
if(!isset($_POST['assign1'])) {
$score[0] = null;
}else {
$score[0] = $_POST['assign1'];
echo "<h2>Assignment 1:</h2>" . $score[0] . "</br>";
}
if(!isset($_POST['assign2'])) {
$score[1] = null;
}else {
$score[1] = $_POST['assign2'];
echo "<h2>Assignment 2:</h2>" . $score[1] . "</br>";
}
if(!isset($_POST['assign3'])) {
$score[2] = null;
}else {
$score[2] = $_POST['assign3'];
echo "<h2>Assignment 3:</h2>" . $score[2] . "</br>";
}
if(!isset($_POST['assign4'])) {
$score[3] = null;
}else {
$score[3] = $_POST['assign4'];
echo "<h2>Assignment 4:</h2>" . $score[3] . "</br>";
}
if(!isset($_POST['assign5'])) {
$score[4] = null;
}else {
$score[4] = $_POST['assign5'];
echo "<h2>Assignment 5:</h2>" . $score[4] . "</br>";
}
if(!isset($_POST['assign6'])) {
$score[5] = null;
}else {
$score[5] = $_POST['assign6'];
echo "<h2>Assignment 6:</h2>" . $score[5] . "</br>";
}
if(!isset($_POST['assign7'])) {
$score[6] = null;
}else {
$score[6] = $_POST['assign7'];
echo "<h2>Assignment 7:</h2>" . $score[6] . "</br>";
}
if(!isset($_POST['assign8'])) {
$score[7] = null;
}else {
$score[7] = $_POST['assign8'];
echo "<h2>Assignment 8:</h2>" . $score[7] . "</br>";
}
if(!isset($_POST['assign9'])) {
$score[8] = null;
}else {
$score[8] = $_POST['assign9'];
echo "<h2>Assignment 9:</h2>" . $score[8] . "</br>";
}
if(!isset($_POST['assign10'])) {
$score[9] = null;
}else {
$score[9] = $_POST['assign10'];
echo "<h2>Assignment 10:</h2>" . $score[9] . "</br>";
}
if(!isset($_POST['assign11'])) {
$score[10] = null;
}else {
$score[10] = $_POST['assign11'];
echo "<h2>Assignment 11:</h2>" . $score[10] . "</br>";
}
if(!isset($_POST['assign12'])) {
$score[11] = null;
}else {
$score[11] = $_POST['assign12'];
echo "<h2>Assignment 12:</h2>" . $score[11] . "</br>";
}
if(!isset($_POST['assign13'])) {
$score[12] = null;
}else {
$score[12] = $_POST['assign13'];
echo "<h2>Assignment 13:</h2>" . $score[12] . "</br>";
}
if(!isset($_POST['assign14'])) {
$score[13] = null;
}else {
$score[13] = $_POST['assign14'];
echo "<h2>Assignment 14:</h2>" . $score[13] . "</br>";
}
if(!isset($_POST['assign15'])) {
$score[14] = null;
}else {
$score[14] = $_POST['assign15'];
echo "<h2>Assignment 15:</h2>" . $score[14] . "</br>";
}
if(!isset($_POST['assign16'])) {
$score[15] = null;
}else {
$score[15] = $_POST['assign16'];
echo "<h2>Assignment 16:</h2>" . $score[15] . "</br>";
}
if(!isset($_POST['assign17'])) {
$score[16] = null;
}else {
$score[16] = $_POST['assign17'];
echo "<h2>Assignment 17:</h2>" . $score[16] . "</br>";
}
if(!isset($_POST['assign18'])) {
$score[17] = null;
}else {
$score[17] = $_POST['assign18'];
echo "<h2>Assignment 18:</h2>" . $score[17] . "</br>";
}
if(!isset($_POST['assign19'])) {
$score[18] = null;
}else {
$score[18] = $_POST['assign19'];
echo "<h2>Assignment 19:</h2>" . $score[18] . "</br>";
}
if(!isset($_POST['assign20'])) {
$score[19] = null;
}else {
$score[19] = $_POST['assign20'];
echo "<h2>Assignment 20:</h2>" . $score[19] . "</br>";
}
?>
<?php
$sum = array_sum($score);
$num_elements = count($score);
echo "<h2>Assignments Completed:</h2>" . $num_elements .
"</br>";
echo "<h2>Assignments Score Total:</h2>" . $sum .
"</br>";
?>
</div>
</body>
</html>
To expand on Alex Howansky's answer, you'll need to turn your <input> fields into an array (see How do I create arrays in a HTML form? in PHP's manual).
To do that, just replace all input fields with:
<input type="text" name="assign[]"><br />
Afterwards, you can loop them like so (this would replace your PHP code in arraysolo.php):
$score = [];
foreach ($_POST['assign'] ?? [] as $key => $value) {
$is_valid = is_numeric($value) && $value >= 0 && $value <= 200;
if ($is_valid) {
$score[] = $value;
echo "<h2>Assignment " . ($key + 1) . ":</h2>" . $value . "</br>";
}
}
$sum = array_sum($score);
$num_elements = count($score);
echo "<h2>Assignments Completed:</h2>" . $num_elements . "</br>";
echo "<h2>Assignments Score Total:</h2>" . $sum . "</br>";
This way, you'll also don't have to filter for any null values (because you won't assign them in the first place).

Not Able to save data to Mysql database

I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.

Loop form in PHP, Submit all forms with 1 button

I have a question. I want to make a history timeline, on this timeline the user can add 'elements' (e.g. a element for each year.).
In form 1 the user creates timeline and says the amount of elements on the timeline this gets send to the database (this works).
In form 2 the user can fill the elements. (This doesnt work).
In form 1 (if someone wants 5 elements) after posting, the database creates 5 records (for each element one).
Now I want 5 different forms that fills these 5 elements (Title, description etc.), but with 1 submit button.
Now if i try this (see code below), only the 5th form gets posted...
How do I get this to work?
Thanks in advance,
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('classes/database.class.php');
$DB = Database::getInstance();
$titel = '';
$beschrijving = '';
$afbeeldingURL = '';
$jaar = '';
$element_id = '';
$velden = '';
$sql3 = "SELECT `id` , `aantal_elementen` FROM `tijdlijn` ORDER BY id DESC LIMIT 0, 1";
$last_id = $DB->_query($sql3);
if ($last_id->num_rows > 0) {
while($row = $last_id->fetch_assoc()) {
$last_id2 = $row["id"];
$aantal_elementen3 = $row["aantal_elementen"];
}
}
$sql4 = "SELECT * FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2."";
$sql5 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id ASC LIMIT 0,1";
$sql6 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id DESC LIMIT 0,1";
$sql7 = "SELECT `id` FROM `elementen` WHERE `tijdlijn_id` = ".$last_id2." ORDER BY id ASC";
$last_id3 = $DB->_query($sql4);
$min_id = $DB->_query($sql5);
$min_id = mysqli_fetch_assoc($min_id);
$min_id = $min_id['id'];
$max_id = $DB->_query($sql6);
$max_id = mysqli_fetch_assoc($max_id);
$max_id = $max_id['id'];
$dingid[] = $DB->_query($sql7);
echo $min_id."</br>";
echo $max_id."</br>";
$current_id = $min_id;
if (isset($_POST) && !empty($_POST)) {
$boolError = false;
foreach ($_POST as $k => $v) {
$_POST[$k] = trim($v);
}
if (!isset($_POST['titel']) || trim($_POST['titel']) == '') {
$titel = 'error';
$boolError = true;
}
if (!isset($_POST['beschrijving']) || trim($_POST['beschrijving']) == '') {
$beschrijving = 'error';
$boolError = true;
}
if (!isset($_POST['afbeeldingURL']) || trim($_POST['afbeeldingURL']) == '') {
}
if (!isset($_POST['jaar']) || trim($_POST['jaar']) == '') {
$jaar_start = 'error';
$boolError = true;
}
if (
!isset($_POST['element_id'])
|| trim($_POST['element_id']) == ''
|| !preg_match('/^\d+$/', $_POST['element_id'])
) {
$element_id = 'error';
$boolError = true;
}
if ($boolError === false) {
$sql = "UPDATE `elementen`
SET
`titel` = '" . $_POST['titel'] . "',
`beschrijving` = '" . $_POST['beschrijving'] . "',
`afbeelding_url` = '" . $_POST['afbeeldingURL'] . "',
`jaar` = '" . $_POST['jaar'] . "'
WHERE `id` = ".$_POST['element_id'].";
";
if ($DB->_query($sql)) {
//$current_id++;
//exit;
} else {
header('Location: ?oops2');
exit;
}
} else {
$velden = "Ff alles invullen he";
}
?> <p>Vul het formulier hier onder in voor de elementen en maak een tijdlijn!</p><?php
}
if ($last_id3->num_rows > 0) {
while($row2 = $last_id3->fetch_assoc()) {
$last_id4 = $row2["id"];
?>
<form class="form-nieuws" method="post">
</br></br>
<?php echo $last_id2; ?>
<?php echo $current_id; ?>
<input id="titel2" class="<?= $titel ?> form-control" type="text" placeholder="Titel tijdlijn" name="titel" value="<?= isset($_POST['titel']) ? $_POST['titel'] : '' ?>">
<br>
<textarea id="beschrijving2" class="<?= $beschrijving ?> form-control" rows="3" placeholder="Beschrijving over tijdlijn" name="beschrijving" value="<?= isset($_POST['beschrijving']) ? $_POST['beschrijving'] : '' ?>"></textarea>
<br>
<input id="afbeeldingURL2" class="<?= $afbeeldingURL ?> form-control" type="text" placeholder="URL voor afbeelding" name="afbeeldingURL" value="<?= isset($_POST['afbeeldingURL']) ? $_POST['afbeeldingURL'] : '' ?>">
<br>
<input id="jaar" class="<?= $jaar ?> form-control" type="text" placeholder="Start jaar tijdlijn" name="jaar" value="<?= isset($_POST['jaar']) ? $_POST['jaar'] : '' ?>">
<input id="element_id" class="<?= $element_id ?> form-control" type="text" placeholder="<?php echo $last_id4 ?>" name="element_id" value="<?= isset($_POST['element_id']) ? $_POST['element_id'] : '' ?>">
<div class="foutlabel">
<em class="<?= ($velden) ? 'error' : '' ?>"><?= ($velden) ? $velden : '' ?>
</em>
</div>
</br>
<?php $current_id++;}
} ?> <div class="gabutton">
<input type="submit" value="Creeer tijdlijn">
</div>
</form>
The best way is to have only one form with input for each elements. You generate each form input in function of your elements.
With this way, you only have one button and one call to send data to your server.
In server side, you just need to parse and check data and be carefull about number of element you send.

Insert several rows at once MySql DB

I have a form with 6 text inputs for users to add some links to them and add them do a database. Each one of these 6 inputs insert data in a different row. This is my code:
public function insertImages($img1,$img2,$img3,$img4,$img5,$img6){
$myDb = $this->_controlPanel->getMyDb();
$query = "INSERT INTO galeria (img) VALUES ('$img1'), ('$img2'),('$img3'), ('$img4'),('$img5'), ('$img6')";
$result = $myDb->performQuery($query);
if (!$result) {
die('Something went wrong, try again: ' . mysql_error());
header( "Refresh:3; url=insertnot.php");
}
else {
header( "Refresh:1; url=admin.php");
}
}
and
if(!empty($_POST)){
$img1 = $_POST['img1'];
$img2 = $_POST['img2'];
$img3 = $_POST['img3'];
$img4 = $_POST['img4'];
$img5 = $_POST['img5'];
$img6 = $_POST['img6'];
try{
$log = new classes_UserManager($myControlPanel);
$insert = $log->insertImagens($img1,$img2,$img3,$img4,$img5,$img6);
}
catch (invalidArgumentException $e){
$e->getMessage();
}
}
?>
<div class="container">
<h2 style="color:#666; margin-top:15vh; text-align:center;"> Inserir Imagens </h2>
<form style="margin-top:10vh;" name="img" method="POST" action="">
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 1" class="form-control" type="text" name="img1" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 2" class="form-control" type="text" name="img2" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 3" class="form-control" type="text" name="img3" id="title" >
</div>
</div>
<br>
<br>
<div class="row">
<div class="col-md-4">
<input placeholder="Imagem 4" class="form-control" type="text" name="img4" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 5" class="form-control" type="text" name="img5" id="title" >
</div>
<div class="col-md-4">
<input placeholder="Imagem 6" class="form-control" type="text" name="img6" id="title" >
</div>
</div>
<br>
<br>
<input type="submit" style="width:100%; margin:0 auto;" class="btn btn-primary form-control" name="submit" id="submit">
This is working well, but how do i avoid entering blank rows when the user only fills like two or three inputs?
Use the "power" of concatenation. There are few solutions to your problem.
let's consider following function:
<?php
// get all non-empty fields for POST that
// have index like img<number>
function getNonEmptyValues ($inputs , $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
}
return $nonempty_inputs;
}
// get all non-empty fields for POST that
// have index like img<number>
// but ignore all fields after 1 missing,
// e.g. : img1, img2, img3 return array of length 3
// while img1, img2, img4 will return array of length 2
function getInOrder($inputs, $input_prefix, $inputs_count = 7)
{
$nonempty_inputs = array();
$prefix = isset($input_prefix) ? $input_prefix : '';
// you have to be sure each of your inputs
// is indexed as range 1..N
// with some prefix
for ($i = 1; $i < $inputs_count; $i++)
{
$value = isset($inputs[$prefix.$i]) ? $inputs[$prefix.$i] : '';
if(strlen($value))
{
$nonempty_inputs []= $value;
}
else
{
break;
}
}
return $nonempty_inputs;
}
function buildInsertQuery ($inputs) {
if (count($inputs) === 0) {
throw new \Exception("Missing inputs. Cannot build query.");
}
$query = "INSERT INTO galeria (img) VALUES ";
$insert_values = [];
foreach( $inputs as $value ) {
$insert_values []= "('".$value."')";
}
return $query . implode(",", $insert_values) . ";";
}
$_our_post = array(
"img1" => "kittenz",
"img2" => "doge",
"img4" => "me gusta"
);
$my_data = getNonEmptyValues($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
$my_data = getInOrder($_our_post, "img");
echo buildInsertQuery($my_data);
echo "\n";
something like this:
if(!empty($_POST)) {
$images = array();
for ($i = 1; $i <= 6; $i++) {
if (!empty($_POST['img'.$i]))
$images[] = $_POST['img'.$i];
}
if (sizeof($images) > 0)
$insert = $log->insertImages($images);
...
}
and
public function insertImages($images) {
$myDb = $this->_controlPanel->getMyDb();
$imgStr = '';
foreach($images as $k => $v) {
$imgStr += "('$v'),";
}
$imgStr = rtrim($imgStr, ','); // remove trailing comma
$query = "INSERT INTO galeria (img) VALUES $imgStr";
...
}

multiple - same name radio

I'm starting to make a little quiz page, where there are 3 choices opportunities. I here by to find out about what it is right,
Html
<p><input type="radio" name="svar[1]"><?php echo $svar1;?></p>
<p><input type="radio" name="svar[2]"><?php echo $svar2;?></p>
<p><input type="radio" name="svar[3]"><?php echo $svar3;?></p>
Php
if($_POST["svar"][1] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][2] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][3] == $ok)
{
$_POST["rigtigok"] = 1;
}
what I would like it / it must be outward is $ok is true with what comes from the database
if it shows like this:
$_POST["svar"][3] == $ok
then it will at the same time the $ok = 3
then it will also say that the content fits with what is being clicked by radio contents.
My Content from the database looks like this:
<form action="#" method="post">
<?php
if ($stmt = $this->mysqli->prepare('SELECT id, title, svar1, svar2, svar3, ok FROM quiz ORDER BY RAND() LIMIT 1')) {
$stmt->execute();
$stmt->bind_result($id, $title, $svar1, $svar2, $svar3, $ok);
while ($stmt->fetch()) {
?>
<h3><?php echo $title;?></h3>
<div style="padding:5px 10px;">
<p><input type="radio" name="svar[1]"><?php echo $svar1;?></p>
<p><input type="radio" name="svar[2]"><?php echo $svar2;?></p>
<p><input type="radio" name="svar[3]"><?php echo $svar3;?></p>
</div>
<?php
if(isset($_POST["ok"]))
{
if($_POST["svar"][1] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][2] == $ok)
{
$_POST["rigtigok"] = 1;
}
elseif($_POST["svar"][3] == $ok)
{
$_POST["rigtigok"] = 1;
}
}
}
$stmt->close();
} else {
echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
}
?>
<br/>
<input type="submit" name="ok" value="Nyt Spørgsmål" class="new upload_boxxen">
</form>
<?php
echo print_r($_POST["svar"]);
if(isset($_POST["ok"]))
{
if($_POST["rigtigok"] == 1)
{
echo "test";
}
}
EDIT
How it is that I do not get anything out of $_POST["rigtigok"] to be the first me later that I can give my 3 points for his correct answer?

Categories