I have some checkboxes with printed values according to the database which are working fine.When I submit the form it gives me an error saying that the variable which I posted from the checkboxes array is not defined and that way I cant insert the values in the database.
The PHP code to post the array and insert in the database:
//The posts above don't matter because the first query works just fine
$candCurso = $_POST['curso'];
$query = "INSERT INTO tbl_candidatos(cand_nome, cand_datanasc, cand_nac, cand_nat, cand_gen, cand_morada, cand_codpost, cand_cidade, cand_email, cand_telefone, cand_telemovel, cand_tipodoc, cand_ndoc, cand_valdoc, cand_nif, cand_hablit, cand_sitprof, cand_grau, cand_instgrau, cand_datagrau, cand_instfunc, datainsc) VALUES ('$candNome','$candDataNasc','$candNac','$candNat','$candGen','$candMorada' ,'$candCodPost','$candCidade','$candEmail','$candTelefone','$candTelemovel','$candTipoDoc','$candNDoc','$candValDoc', '$candNif','$candHabLit','$candSitProf','$candGrau','$candInstGrau', ' $candDataGrau','$candInstFunc', '$dins')";
$result = mysqli_query($link, $query); // Executa a instrução MYSQL
if($result){
echo "<script>alert('I entered the result if');</script>";
$lastID = mysqli_insert_id($link);
foreach($candCurso as $value) {
echo "<script>alert('I entered the foreach if');</script>";
$data = date('Y-m-d');
$sql = "INSERT INTO tbl_professor_curso(cand_id, cur_id, data_admissao) VALUES ($lastID, '$value', '$data')";
$rr = mysqli_query($link, $sql); // Executa a instrução
}
The code doesn't run the foreach statement because of the variable $candCurso.
The form:
<!-- Message -->
<div class="col-md-12">
<!-- Form Group -->
<div class="form-group">
<label for="form_message">Select *</label>
<?php
$cursos = getCursos($link);
foreach ($cursos as $curso): ?>
<div class="checkbox">
<label >
<input type="checkbox" class="form-control" name="curso[]" value="<?= $curso['cur_id'] ?>"> <?= $curso['cur_nome'] ?>
</label>
</div>
<?php
endforeach;
?>
</div><!-- /End Form Group -->
</div><!-- /End Message -->
Any help is appreciated as I'm looking to fix this for hours.
Related
i want to add commenting to each article, so inside my"foreach"cycle I added commenting to each article, but "set a comment" function runs to all art
thats the code for making an article window
<?php $articles_qr = mysqli_query($connection, "SELECT * FROM `articles` ");
$articles = array();
while ( $art = mysqli_fetch_assoc($articles_qr))
{
$articles[] = $art;
}
?>
<?php foreach ($articles as $art)
{
?>
<section>
<div class="containerstuff">
<div class="stuffpic">
<img src="<?php echo "../static/imagespages/",$art['image'] ?>" class="pico">
</div>
<div class="article">
<h1><?php
echo $art['title']
?>
</h1>
<?php
echo $art['text'];
echo $art['id']
?>
</div>
</div>
<div class="scrollmenu">
<?php include "../includes/comments.php";?>
</section>
<?php
} ?>
thats the code comments window
<?php
date_default_timezone_set(timezone_identifier);
include_once '../comments.ink.php'
?>
<div class="containercom">
<img src="#" class="commpic">
<p class="comment"></p>
</div>
<div class="blockcom">
<form class='form' method='POST' action="<?php echo setComments($connection)?>">
<div class='form__group'>
<input type='hidden' name='page_id' value="<?php echo $art['id']?>" >
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='pubdate' value="<?php echo date('Y-m-d H:i:s')?>" >
<textarea name='text' class='form__control' placeholder ='Введите комментарий...' required=''></textarea>
</div>
<div class='form__group'>
<input type='submit' class='form__control2' name='commentSubmit'></input>
</div>
</div>
</form>
and thats the code for INSERT function
<?php
static $firstTime = true;
function setComments($connection) {
if(isset($_POST['commentSubmit'])){
$idcom = $_POST['page_id'];
$uid = $_POST['uid'];
$pubdate = $_POST['pubdate'];
$text = $_POST['text'];
$sql =
"INSERT INTO `comments` (page_id, uid, pubdate, text)
VALUES ('$idcom', '$uid', '$pubdate', '$text')";
$result = $connection->query($sql);
$firstTime = false;
}
}
so how can i make insert only for 1 article (so when i add it now, there are appears as many comments as many articles i have in database)
I think you should use ajax to append a new comment which is the widely used solution, the way u r doing will become difficult to handle for you.
I haven't found the solution, so I just selected another way.
For each article I placed a button to post a comment which will send user to the page with this article and for this button for "href" I wrote php code (href = "comments.php?id=<?php echo $art['id']"?>) and for this page I use $_GET to select articles only for this id. Then I just placed there comments-function that I wrote so it works alright now because function works only for 1 argument
I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!
My prepared statements for inserting data into a database are not working. I have had these issues accross the board but I am including one example just incase I am making a simple mistake. The query is running ok as I am getting a message which I placed myself within the code, however nothing is being entered into the actual database. MY issues so far with prepared statements is the lack of feedback you get when something isnt working. Any help would be greatly appreciated.
<?php
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level,
price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject,
$newlevel, $newprice);
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
HTML for form:
<form enctype="multipart/form-data" action='updatesubjects.php' method="post" id="update-subjects-form" name="new-subject" >
<fieldset>
<!--Tutor ID (Posted from previous page) -->
<input type="hidden" name="tutorId" value='<?php echo "$userarray[0]";?>'>
<!-- Subject -->
<div class="form-group">
<label for="subjects">Subject</label>
<select name="subjects" type="text" class="form-control">
<?php
if(mysqli_num_rows($subjectsresult)>0){
while($row = mysqli_fetch_assoc($subjectsresult)){
$get_subjectid = $row['subject_id'];
$get_subjectname = $row['subject'];
echo "<option value='$get_subjectid'>$get_subjectname</option>";
}
}
?>
</select>
</div>
<!-- Level -->
<div class="form-group">
<label for="subjectlevel">Subject Level</label>
<select name="subjectlevel" type="text" class="form-control">
<?php
if(mysqli_num_rows($levelresult) > 0){
while($row = mysqli_fetch_assoc($levelresult)){
$get_levelid = $row['level_id'];
$get_namelevel = $row['level'];
echo "<option value='$get_levelid'>$get_namelevel</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label for="subjectlevel">Price</label>
<input type='number' step='0.01' min='0' name='price'>
</div>
<button class="btn btn-primary" type="submit" name="newsubject" id="bookingsform">Submit form</button>
</fieldset>
</form>
I apologies for any poor indentation
You need to declare your variables and assign value to them before binding. At the moment you should have undefined variables.
On development environment ensure error reporting is on.
<?php
error_reporting(-1);
ini_set('display_errors', 1);
if(isset($_POST['newsubject'])){
include('../connection/conn.php');
//Set Values
$newtutor = $_POST["tutorId"];
$newsubject = $_POST["subjects"];
$newlevel = $_POST["subjectlevel"];
$newprice = $_POST["price"];
//Prepare the insert statement
$insertquery = "INSERT INTO miiLearning_Tutors(tutor_id,subject_level, price, subjects) VALUES (?,?,?,?)";
if($stmt = mysqli_prepare($conn, $insertquery)){
//bind variable to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "iidi", $newtutor, $newsubject, $newlevel, $newprice);
mysqli_stmt_execute($stmt);
echo"<p>Query Ran</p>";
} else{
echo "ERROR: Could not prepare query: $query . " .mysqli_error($conn);
}
}
?>
I'm trying to do an update page, the data that I'm fetching are input texts, dates, dropdowns and a textarea.
The data on input texts & date works completely fine however, the data on my dropdowns and textarea wont appear.
I still can update it, the only problem here is it just won't appear. So I'm hoping if anybody can help me and see what I missed in my coding.
How my form looks like:
Solution:
I've found the solution to this question and below is my new html coding. There a few php coding that I edited at the dropdown and the dates.
Updated html code:
php code that are outside from my html:
<?php
session_start();
require('db.php');
include("auth.php");
$noID=$_REQUEST['noID'];
$query = "SELECT * from daftartempah where noID='".$noID."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
php code that are inside my html:
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$noID=$_REQUEST['noID'];
$trn_date = date("Y-m-d H:i:s");
$pemohon =$_REQUEST['pemohon'];
$trkhMula = $_REQUEST['trkhMula'];
$trkhAkhir =$_REQUEST['trkhAkhir'];
$n_program = $_REQUEST['n_program'];
$lokasi =$_REQUEST['lokasi'];
$n_anjuran = $_REQUEST['n_anjuran'];
$catatan = $_REQUEST['catatan'];
$status_hr = $_REQUEST['status_hr'];
$submittedby = $_SESSION["username"];
$update="update daftartempah set trn_date='".$trn_date."', pemohon='".$pemohon."', trkhMula='".$trkhMula."', trkhAkhir='".$trkhAkhir."', n_program='".$n_program."', lokasi='".$lokasi."', n_anjuran='".$n_anjuran."', catatan='".$catatan."', status_hr='".$status_hr."', submittedby='".$submittedby."' where noID='".$noID."'";
mysqli_query($con, $update) or die(mysqli_error());
$status = "Record Updated Successfully. </br></br>
<a href='Page8.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
Dropdowns:
<div class="form-group row text-left">
<label for="example-text-input" class="col-3 col-form-label"><b>Dept/Kelab/Anjuran: </b></label>
<div class="col-8">
<select class="form-control" name="n_anjuran" id="namaAnjuran">
<option selected name="" value="<?php echo $row['n_anjuran'];?>"><?php echo $row['n_anjuran'];?></option>
<?php
$sql = mysqli_query($con, "SELECT kd_dept, desc_dept From koddept");
$rows = mysqli_num_rows($sql);
while ($rows = mysqli_fetch_array($sql)){
echo "<option value='". $rows['kd_dept'] ."'>" .$rows['desc_dept'] ."</option>" ;
}
?>
</select>
</div>
</div>
Textarea:
<div class="form-group row text-left">
<label for="exampleTextarea" class="col-3 col-form-label"><b>Catatan: </b></label>
<div class="col-8">
<textarea class="form-control" rows="3" name="catatan" required><?php echo $row['catatan'];?></textarea>
</div>
</div>
My new form:
All questions are welcome, feel free to comment and ask, I'll try to help.
In the folowing code I am doing an insert from a form into a mysql table
The form fields are populated from an MySQL database, which work correctly.
The problem is extracting data from the multiple checkboxes and inserting each value as a new row in the same table 'selection' columns userid and videoid.
The userid field is inserted correctly, but the videoid is not posting any data.
<?php
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect");//connection string
$user=$_POST['userid'];
$checkbox1=$_POST['videoid'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1.",";
}
$in_ch=mysqli_query($con,"INSERT INTO tbl_selection (userid, videoid) VALUES ('$user', '$chk');");
if($in_ch==1)
{
echo'<script>alert("Inserted Successfully")</script>';
}
else
{
echo'<script>alert("Failed To Insert")</script>';
}
}
?>
</body>
</html>
This is the html form which is populated from a mysql table:
<?php
connect to database
?>
<div class="control-group">
<?php
$query = "SELECT * FROM video";
$result2 = mysql_query($query);
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="videoid" value="<?php echo $line[id]?>"><?php echo $line[title]?>
</label>
</div>
<?php } ?>
1) Change
<input type="checkbox" name="videoid" value="<?php echo $line[id]?>"><?php echo $line['title']?>
To
<input type="checkbox" name="videoid[]" value="<?php echo $line[id]?>"><?php echo $line['title']?>
Means, for multiple checkbox. Use name as array type. Like videoid[].
2) Use for or foreach loop for inserting multiple checkbox value into a table. First, find out the checked checkbox through sizeof. Then, use accordingly.
Updated Code
<?php
$con=mysqli_connect("$host", "$username","$password","$db_name")or die("cannot connect");
$user=$_POST['userid'];
$videoCheckBox=$_POST['videoid'];
$checkedVideo = sizeof($videoCheckBox);
for($i=0;$i<$checkedVideo;$i++) {
$videoId = $videoCheckBox[$i];
$queryVideo = mysqli_query($con,"INSERT INTO `tbl_selection` (`userid`, `videoid`) VALUES ('$user', '$videoId');");
}
if($checkedVideo == 0) {
echo'<script>alert("Failed To Insert")</script>';
} elseif($queryVideo) {
echo'<script>alert("Inserted Successfully")</script>';
}
?>
</body>
</html>
<div class="control-group">
<?php
$query = "SELECT * FROM video";
$result2 = mysql_query($query);
while ($line = mysql_fetch_array($result2, MYSQL_ASSOC)) {
?>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="videoid[]" value="<?php echo $line['id']?>"><?php echo $line['title']?>
</label>
</div>
<?php } ?>
For more info, please click Inserting data into mySQL table from mutlidimensional input form