dynamic empty field should not be stored in database - php

Here I'm stored some array values into database successfully. But, I have a problem here. For example : I have four input textfields. Assume if user filled three textfields and remaining one field is empty. When I execute this code I got 4 rows in my db table. 3 rows with values and one row without a value (empty field). (I DONT NEED THAT ONE ROW WITHOUT A VALUE)
But, I need if user didn't entered one field that field should not be stored in database. How to do that? I have posted my codes and image below.
<?php
include('config.php');
if(isset($_POST['submit']))
{
$cqty = $_POST['qty'];
foreach( $cqty as $key => $n )
{
echo $n ."<br/>";
try
{
$stmt = $conn->prepare("INSERT INTO testing ( qty ) VALUES ( :n )");
$conn->errorInfo();
$stmt->bindParam(':n', $n, PDO::PARAM_STR);
$stmt->execute();
}
catch (PDOException $e)
{
$e->getMessage();
}
}
if($stmt)
{
echo "inserted";
}
else
{
die(mysql_error());
}
}
?>
and
<form action="db.php" method="post">
qty : <input type="text" name="qty[]" /><br />
<input type="submit" name="submit" value="Submit" />
</form>

Use empty to check if $n is empty. Use continue to skip the rest of the instruction in the foreach loop for that iteration.
foreach( $cqty as $key => $n )
if (empty($n)) continue;
echo $n ."<br/>";
try ...

Related

form action inside foreach works only for the first value of php

I have created a form where every time, it would store a different id during foreach loop
<?php
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php
}
?>
and the retrieval of the data works perfectly, it shows me each and every id one after another, but when I click the button (in this case to clear the item) it only works for the first value i.e. if I click the button for the second or the third value, it deletes the first one only, not the one corresponding to the button.
please do help, why this is happening and the appropriate solution, if anyone can provide!
the clearitem.php
if(isset($_POST['clearitem'])){
$clear=$_POST['clearitem'];
$sql = "DELETE FROM cart WHERE id=".$clear;
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully of id".$clear;
} else {
echo "Error deleting record: " . $conn->error;
}
}
So, I was able to solve this issue, and the solution is the "id" so when you are using foreach, for every iteration, it is re-creating the form with the different value of the input, of course!
But the problem is the id-field, even if the input value is different, but the id is same for every iteration and therefore, even if you click a different button i.e. the 2nd or 3rd, the POST request will consider the initial value as the actual value, i.e. the first iteration, just because the id was same!
It's similar to the concept of first-come-first-serve. Since the POST request getting the value of the first element correspondent to the id, therefore that will the final value of that specific id and no amount how many times you iterate, the value will not be updated if you use the same id.
The possible fix is to have a different id, with each different iteration and that was made possible with putting the foreach value in the id.
<?php
foreach ($res as $r) {
?>
<form id="clearitem<?php echo $r['cart_id'];?>" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php
}
?>
by this for every iteration, the value of the id will be different, like if cart_id are as:1, 2, 3 then the ids would be clearitem1, clearitem2, clearitem3. By this the POST request will be retrieving different values since the ids are different!
The system should be able to correctly process the submitted data according to the data value in each form in such a "multi-form" environment.
Hence the code below should work (tested):
<?php
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "SELECT * FROM cart";
$stmt = $conn->prepare($sql);
$stmt->execute();
$res = $stmt->get_result();
foreach ($res as $r) {
?>
<form id="clearitem" action="clearitem.php" method="POST" enctype="multipart/form-data">
<input type="text" name="clearitem" value="<?php echo $r['cart_id'];?>">
<button type="Submit">×</button>
</form>
<?php } ?>
The following is the clearitem.php code
<?php
if (isset($_POST["clearitem"])) {
$conn = new mysqli("localhost","dbuser","dbpassword","dbname");
$sql = "delete FROM cart where cart_id=?" ;
$stmt = $conn->prepare($sql);
$id=$_POST["clearitem"];
$stmt->bind_param("i", $id);
$stmt->execute();
}
?>
<script>
alert("Done !");
if ('referrer' in document) {
window.location = document.referrer;
/* OR */
//location.replace(document.referrer);
} else {
window.history.back();
}
</script>

mysqli insert into database from multiple checkbox with foreach

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) ...

Array ( ['1'] => 1 ) 1 Notice: Undefined offset: 1 in C:\xampp\htdocs\HR\functions\functions_applicants.php on line 152 2

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.

Delete statement using PDO, PHP and MYSQL using primaryKey & checkBox

I'm trying to delete multiple entry in database. I'm using a checkbox to determine what data I need to delete. Once I tick the checkbox, its sending me the value of my primary key which I use to delete it. So far I have come up with this
when I try to delete single or multiple data, it goes straight to success page which successfully count the number of intended amount of deleted player. But nothing happens when I show all tables.
HTML/PHP code
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
echo "<form id='delete' method='POST' action='$self'>";
?>
<div class="content">
<h3>Delete Athlete</h3>
<hr>
<table>
<tr>
<th>Select Player</th><th>Photo</th><th>First Name</th><th>Last Name</th><th>Gender</th><th>Sport</th><th>Country</th><th>Population</th><th>Flag</th>
</tr>
<?php
foreach($showResult as $row)
{
echo("<tr><td><input type='checkbox' name='checkdelete[]' value='$row[athleteID]'>$row[athleteID]</td>
<td><img class='photo' src='files/$row[image]' alt='$row[lastName].jpg'/></td>
<td>$row[firstName]</td><td>$row[lastName]</td>
<td><img class='genderImg' src='files/$row[gender].png' alt='$row[gender].jpg'/></td>
<td>$row[sport]</td><td>$row[countryName]</td><td>$row[population]</td>
<td><img class = 'flag' src='files/flags/$row[flag]' alt='$row[flag].jpg'/></tr>");
}
?>
</table>
<br><input type="submit" name="deleteAth" value="Delete">
</div>
</body>
and I have this code for PHP
<?php
include 'connect.inc.php';
try // select statement for the output page/delete page
{
$showJoinedTbl = "SELECT athleteID,image, firstName, lastName, gender, sport,
countryName, population, flag from athTbl join
counTbl on athTbl.countryID = counTbl.countryID ORDER by firstName";
$showResult = $pdo->query($showJoinedTbl);
}
catch (PDOException $e)
{
$error = 'Select statement error';
include 'error.html.php';
exit();
}
$dataCorrect = true;
if (isset($_POST['deleteAth']))
{
try
{
$valueID = $_POST['checkdelete'];
$N = count ($valueID);
for ($i=0; $i; $i++)
{
$deleteQry = $db->prepare("DELETE from athTbl WHERE athleteID= ?");
echo ("$valueID[$i]");
//$stmt = $pdo->prepare($deleteQry);
$stmt->bindValue(1,$valueID[$i]);
$stmt->execute();
} //when I try to delete single or multiple data, it goes straight to success page which successfully count the number of intended amount of deleted player. But nothing happens when I show all tables.
}
catch (PDOException $e)
{
$error = 'Error deleting data from athleteTbl';
include 'error.html.php';
exit();
}
include 'DeleteSuccess.html.php'; // output screen if I deleted it successfully.
}
else
{
include 'Delete.html.php';
}
?>
You have an error in your loop:
...
$N = count ($valueID);
for ($i=0; $i; $i++)
^^ 0 on the first iteration
{
...
Your loop will run while the condition (the middle value) is true. You set $i to 0 which evaluates to false so your loop never runs.
Or, from the manual:
In the beginning of each iteration, expr2 is evaluated. If it
evaluates to TRUE, the loop continues and the nested statement(s) are
executed. If it evaluates to FALSE, the execution of the loop ends.
You probably want:
...
$N = count ($valueID);
for ($i=0; $i < $N; $i++)
{
...

Multiple checkboxes inserting improperly

I've researched this for two days and just about have it working... trouble is, when I check TWO checkboxes on my dynamically populated form, I get FOUR records inserted. It gets weirder... ONE of the records is unique. THREE have the same information. I'm totally lost here.
Here is the code for the form:
<form name="form1" id="form1" method="post" action="insert_zip_codes.php?u=<?php echo $_SESSION['username'] ?>">
<table class="bordered" cellspacing="0">
<tr><th>City</th><th>State</th><th>ZIP Code</th></tr>
<?php while($row = mysql_fetch_array($rs)) { ?>
<tr><td><input name="zip_code[]" type="checkbox" id="zip_code" value="<?php echo $row[zip_code] ?>" /></td><td><?php echo $row[city] ?></td><td><?php echo $row[state] ?></td><td><?php echo $row[zip_code]?></td></tr>
<?php } ?>
</table><br />
<input type="submit" name="Submit" value="Submit" />
</form>
Here is the code for the insert statement on the next page.
<?php $u = $_GET['u']; ?>
<?php var_dump($_REQUEST); ?> </br> </br>`
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query);
}
if(mysql_query($query))
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); ?>
When I hit submit, the following prints out and it inserts successfully into the database.
["zip_code"]=> array(2) { [0]=> string(5) "97477" [1]=> string(5) "97478" }
Looks right, right? But then the database gets these records...
id 40 username *** zip_code 97478
id 41 username *** zip_code 97478
id 42 username *** zip_code 97478
id 43 username *** zip_code 97477
As you can see, the darned thing is entering the first zipcode checked on the page only once (as the fourth record) but is entering the SECOND zipcode first THREE TIMES.
Any idea why? I'm at a loss.
Thank you in advance!!! :)
You are calling mysql_query() 3 times, and with 2 of them outside your foreach() loop, it will insert the last $query/$zip_code an additional 2 times.
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
mysql_query($query); // 1st time (does query foreach zip_code)
}
if(mysql_query($query)) // 2nd time (does query on last zip_code a second time)
{
echo 'success';
}
else
{
echo 'failure' .mysql_error();
}
echo $query; // print the sql to screen for de-bugging
$results = mysql_query($query); // 3rd time (does query on last zip_code a third time) ?>
Removing the last one, as it is just there for de-bugging, you could change your loop code to -
<?php foreach ($_POST['zip_code'] as $zip_code) {
$query = "INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".$zip_code."')";
$result = mysql_query($query);
if($result)
{
echo 'success ';
}
else
{
echo 'failure' .mysql_error();
}
}
The problem relates to your use of mysql_query() and the $query variable you are using.
Here's a walk through.
You submit two postcodes via $_POST
You loop through the $_POST array and set $query to be the INSERT string.
You then pass that into the function mysql_query() to execute the command to INSERT the record.
So now, you've got two records in your database. You didn't do any checks to see if they worked individually as inserts during that loop (you should have). You also didn't do any escaping to avoid dodgy injection tampering. (you should have).
Anyway, after your loop, this is where it all goes wrong. You then check to see if it worked by running mysql_query($query) again. This is actually going to run the last $query INSERT string you generated again as a command. So that inserts another record into the table.
THEN, you do something with the variable $results by yet again, running the mysql_query($query) command. So that's another record you've inserted.
This means you would have 4 records inserted into your table.
A suggestion
This is off the top of my head! - not tested it
$u = "Whatever";
$inserted = 0;
$fatal = Array();
foreach($_POST['zip_code'] AS $z){
if(mysql_query("INSERT INTO user_zip_save(username, zip_code) VALUES ('$u','".mysql_real_escape_string($z)."')";
$success += mysql_affected_rows();
} else {
$fatal[] = mysql_error();
}
}
echo "Inserted $success of ".count($_POST[zip_code])." records.<br />";
if(count($fatal)){
$fatal = array_unique($fatal);
echo "The following error(s) occurred:<br />";
print "<pre>";
print_r($fatal);
print "</pre>";
}
Hope that helps in some way!

Categories