I stored the data in a supposed to be an array but what happens is that only the last checked checkbox is the only one that is registered in the idSkills. This is the part of the code wherein the skills are displayed through a query in the database
<?php
$i=0;
while ($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills[]" value="<?php echo $id; ?>"><?php echo $skillName; ?><br>
<?php
$i++;
}
?>
Here is the part where the loop unveil all of the selected checkbox
//QUERY TO INSERT
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
$idSkills = $_GET['skills'];
if(empty($idSkills))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($idSkills);
echo("You selected $N door(s): ");
echo("$idSkills[1] ");
for($i=0; $i < $N; $i++) {
echo "Skill ID: "
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('$idSkills[$i]','$idVolunteer')";
$result = $conn->query($sql);
}
}
$conn->close();
It would be best to use a prepared statement instead of substituting a variable into the SQL. But if you're going to do it this way, you need to use the correct syntax:
$sql = "INSERT INTO volunteer_skills (idskill,idVolunteer)
VALUES ('{$idSkills[$i]}','$idVolunteer')";
You need to put {} around an array reference in order to get the variable inside the brackets to be evaluated. See the section on Complex (curly) Syntax in the PHP Strings documentation.
Related
so i tried to get data from my database to checkbox and this is what i have tried :
<?php
$query = "SELECT * FROM siswa WHERE id_tingkatan='$idtingkatan'";
$result = $koneksi->query($query);
while($row=$result->fetch_assoc()){
?>
<input type="checkbox" name="murid[]" value="<?php echo $row['id_siswa']; ? >"><?php echo $row["nama_siswa"]; ?><br><br>
<?php } ?>
and save the value of checked checkbox into database, this is what i have tried :
if(isset($_POST["submit"]))
{
if(!empty ($_POST['murid']))
{
$i= 0;
foreach($_POST as $murid){
$kelas = $_POST['kelas'];
$murid = $_POST['murid'][$i];
$query = "INSERT INTO murid (id_kelas, id_siswa) VALUES ('$kelas', '$murid')";
$q = mysqli_query($koneksi, $query) or die (mysqli_error($koneksi));
$i++;
}
}
else
{
echo "<script type= 'text/javascript'>alert('Pilih minimal 1 siswa');</script>";
header('Location: ./kelas.php');
}
}
when i submit it does input to database but theres one extra row with id_siswa value as 0
The code inserts one record for each value in $_POST. However, $_POST contains all parameters sent (including submit), not just the checkbox array to be inserted. Iterate over the checkbox array $_POST['murid'] instead.
Change
foreach($_POST as $murid) ...
To
foreach($_POST['murid'] as $murid) ...
The code below is to display the quiz(questions and answers)
When submitting, I am getting error:
"Array ( ['1'] => 1 ) 1
Notice: Undefined offset: 1 in C:\xampp\htdocs\HR\functions\functions_applicants.php on line 152
2".
<form method="post" action="index.php?results">
<?php
for($i=1; $i<27; $i++) {
$query = query("SELECT * FROM assess_questions WHERE question_id =$i");
confirm($query);
while($row = fetch_array($query)) {
?>
<div>
<h4><?php echo $row['question']; ?></h4>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=1><?php echo $row['A']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=2><?php echo $row['B']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=3><?php echo $row['C']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=4><?php echo $row['D']; ?><hr>
</div>
<?php
}
}
?>
<input class="btn btn-info" type="submit" name="submit_answers"
value="Next">
</form>
THIS IS THE FUNCTION TO CHECK FOR THE ANSWER. THIS IS WHERE IM GETTING THE ERROR FROM. ITS THE $i that's causing the error.
if(isset($_POST['submit_answers'])) {
$result = 0;
$i = 1;
$average = 0;
$item = ($_POST['quizcheck']);
print_r($item) ;
$query = query("SELECT * FROM assess_questions");
confirm($query);
while($row = fetch_array($query)) {
print_r($row['answer_id']);
$checked = ($row['answer_id']) == $item[$i];
if($checked) {
$result++;
}
$i++;
}
}
The clue is in the contents of $item which you have done a print_r on and got the result:
Array(['1'] => 1)
You're getting this result because in your html your radio buttons are labelled quizcheck['n'] where n is the question id. So presumably in this case you have pressed the first radio button in the first question. You should change the line which gives the radio buttons a name to
<input type="radio" name="quizcheck[<?php echo $row['question_id']; ?>]" value=1><?php echo $row['A']; ?><br>
(i.e. remove the single quotes around <?php echo $row['question_id']; ?>). This will make $item look like:
Array ( [1] => 1 )
so the test
($row['answer_id']) == $item[$i];
will work. Note the parentheses around $row['answer_id'] are unnecessary.
The other issue you are going to run into is that your form obviously doesn't require the user to submit an answer to every question. This means that in your while loop you need to check whether the user has submitted an answer to be checked against the result. If you are not going to make it compulsory to answer all questions, you will need to put an array_key_exists check around the result checking code:
if (array_key_exists($i, $item)) {
$checked = $row['answer_id'] == $item[$i];
if ($checked) {
$result++;
}
}
you begin with $i = 1;
in which case you'll avoid $item[0]; (first position) and it will mismatch $checked = ($row['answer_id']).
start with $i=0; as if there's only one answer $i[1] will not exists but $i[0];
****EDIT****
first check your query result for not being void:
example, having this db connection function/method:
<?php
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli($host, $user, $passwd, $dbName);
return $mysqli;
}catch (Exception $mysqlin){
echo "Error establishing connection with ddbb ".$mysqlin->getMessage();
}
}
?>
And modifying your code:
if(isset($_POST['submit_answers'])) {
$result = 0;
//indexes must start at 0 unless you ensure that you don't need 0 value and your algorithm will not keep trying to get a value out of bounds / array offset
$i = 0;
$average = 0;
//i assume that $_POST['quizcheck'] is an array, otherwise the $item[$i] will be an out of bounds, which match with your issue (array offset). But i ensured some parts of your structure below for you to learn:
$item = ($_POST['quizcheck']);
print_r($item) ;
//you'll must prepare this statement after, for security
$sql = query("SELECT * FROM assess_questions");
//we get the result of this query on $result, if possible
if($result = connection()->query($sql)){
//we get the first row inside $rs (usually called Record Set) as associative (it means that you'll call the values as the column name on DB unless you use AS "Alias" on your query.
$rs = mysqli_fetch_assoc($result);
//if the record set is not void:
while($rs!="") {
//assuming that your DB col is called answer_id
print_r($rs['answer_id']);
//checked will get the value of matching those two arrays, so make sure you control nullables:
if($checked = ($rs['answer_id']) == $item[$i]){
//only if $checked value could be set
if($checked) {
$result++;
}
}
$i++;
}
//repeat this to get the next value, when it has no more values it will be void so it will escape from while loop.
$rs = mysqli_fetch_assoc($result);
}
}
Never assume that you'll get always a value.
Never assume that users will put numbers in some input only because you told them to do it.
Never use dates without checking.
Never state an algorithm with not-controlled vars/function outputs.
Control all data all over across your code and comment it, it will help you to avoid issues and modify your code months after you coded it.
Hope it helps you.
I recommend you to get a hosting to test/code in a controlled environment.
I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}
I'm trying to retrieve all data with the LIKE query from the users input and match it to the database, it works but only returns one record but I have many records in the table.
It returns the closest record it can find,
so say for example I have 2 records who's ItemDesc field contains the characters 'The', when I search for 'The' in my input box and click submit it returns the closest (earliest created) record when it is supposed to return both.
<?php
$username = "a3355896_guy";
$password = "++++++";
$hostname = "mysql5.000webhost.com";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
mysql_select_db("a3355896_book") or die("Unable to connect to database");
$ItemDesc = $_POST['ItemDesc'];
$query = "select * from StockItems where ItemDesc LIKE '%$ItemDesc%'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
?>
Sorry was supposed to included the retrieval:
<?php
if ($num>0)
{
echo "<center><table border=1><tr><th>Item Code</th><th>Item Desc</th>";
echo "<th>Item Stock Qty</th>";
echo "<th>Item Unit Price</th><th>Item Category</th></tr>";
$ItemCode = mysql_result($result,$i,"ItemCode");
$ItemDesc = mysql_result($result,$i,"ItemDesc");
$ItemStockQty = mysql_result($result,$i,"ItemStockQty");
$ItemUnitPrice = mysql_result($result,$i,"ItemUnitPrice");
$ItemCategory = mysql_result($result,$i,"ItemCategory");
echo "<tr><td>$ItemCode</td><td>$ItemDesc</td><td align=right>";
echo "$ItemStockQty</td>";
echo "<td align=right>$ItemUnitPrice</td>";
echo "<td>$ItemCategory</td></tr>";
echo "</table></center>";
}
else
{
echo "<form name='DeleteStock2'>";
echo "<p> Sorry, $ItemDesc does not exist!<p>";
echo "<input type='button' value='Leave' onclick='history.go(-1)'>";
}
?>
You aren't actually accessing your data here- you need to iterate over the result set.
$setLength = mysql_num_rows($result);
for($i = 0; $i < $setLength; $i++){
//Here, mysql_fetch_assoc automatically grabs the next result row on each iteration
$row = mysql_fetch_assoc($result);
//do stuff with "row"
}
Unless you ARE doing that and you just chose to not include it in your snippit. Let us know :)
--Edit--
First off, I apologize- out of old habit I suggested that you use mysql_fetch_assoc instead of the mysqli set of functions.
Try using the fetch_assoc or fetch_array functions, it could solve your issue. I've never used the method you used, I think it has been deprecated for a while.
Check it out here:
http://php.net/manual/en/mysqli-result.fetch-assoc.php
I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>