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

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

Related

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.

PHP- is unable to read the other checked checkbox

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.

update checkboxes after submit

I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)

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!

Display Last entry in first row in a browser

I am creating a form in php with mysql.
When ever a user enter new data then that data automatically saved into database and also displays browser when i want. This form is for displaying mysql data in a browser.
All is working well. but what my problem is when a user submit data then that data displaying last one. but i need to display that details first in a browser.
<?PHP
$connection=Mysql_connect('xxxresource.com','xxx','xxxx');
if(!$connection)
{
echo 'connection is invalid';
}
else
{
Mysql_select_db('tions',$connection);
}
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
//this part goes after the checking of the $_GET var
$fetch = mysql_query("SELECT * FROM customer_details LIMIT $startrow, 10")or
die(mysql_error());
$num=Mysql_num_rows($fetch);
if($num>0)
{
echo "<table margin=auto width=999px border=1>";
echo "<tr><td><b>ID</b></td><td><b>Name</b></td><td><b>Telephone</b></td><td> <b>E-mail</b></td><td><b>Couttry Applying for</b></td><td><b>Visa-Category</b> </td><td><b>Other Category</b></td><td><b>Passport No</b></td><td> <b>Remarks</b></td></tr>";
for($i=0;$i<$num;$i++)
{
$row=mysql_fetch_row($fetch);
echo "<tr>";
echo"<td>$row[0]</td>";
echo"<td>$row[1]</td>";
echo"<td>$row[2]</td>";
echo"<td>$row[3]</td>";
echo"<td>$row[4]</td>";
echo"<td>$row[5]</td>";
echo"<td>$row[6]</td>";
echo"<td>$row[7]</td>";
echo"<td>$row[8]</td>";
echo"</tr>";
}//for
echo"</table>";
}
//now this is the link..
echo '<img align=left height=50px width=50px src="next.png"/>';
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo '<img align=right height=50px width=50px src="previous.png"/>';
?>
My Problem is When a user submit data into mysql database then display that details first in a browser.
Thanks.
You should use ORDER BY clause in your SQL.
SELECT * FROM customer_details ORDER BY ? LIMIT $startrow, 10
Change ? to whichever column you want to sort by.
http://dev.mysql.com/doc/refman/5.0/en/select.html

Categories