I have some PHP displaying an HTML form like this:
And then updates the information in the table when the update button is pressed.
My issue is with the delete option. Any time I hit the update button, the information IS updated successfully, but I get this error message about the delete statement:
Here is the code:
// Info to connect to the Wishlist database
$servername = ".com";
$dbusername = "";
$password = "";
$dbname = "";
try {
// To connect to the database please
$conn = new mysqli($servername, $dbusername, $password, $dbname);
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') '
. $conn->connect_error);
}
echo "Please click <strong><a href = 'http://eggcavity.com/add-wishlist'>here</a></strong> to add creatures to your wishlist.";
if(isset($_POST['submit'])){
$ids = $_POST['ids'];
// Prepare and bind the udpate statement
$sql2 = "UPDATE Wishlists SET Picture = ?, Stage = ?, Gender = ?, Frozen = ?, Notes= ? WHERE ID = ?";
$stmt2 = $conn->prepare($sql2);
$stmt2->bind_param('sssssi', $picture, $stage, $gender, $frozen, $notes, $id);
foreach($ids as $id){
$stagecode = $id . "stage";
$gendercode = $id . "gender";
$frozencode = $id . "frozen";
$notescode = $id . "notes";
$namecode = $id . "creature";
$stage = $_POST[$stagecode];
$Stage = $stage;
$gender = $_POST[$gendercode];
$frozen = $_POST[$frozencode];
$notes = $_POST[$notescode];
$name = $_POST[$namecode];
$sql1 = 'SELECT * FROM Creatures WHERE Name = "' . $name . '"';
$result = mysqli_query($conn, $sql1);
$row = $result->fetch_assoc();
$picture = $row["$stage"];
$stmt2->execute();
}
$theCount = 0;
foreach($_POST['delete'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
echo "Your wishlist has been updated, and" .$theCount. " creature(s) has/have been removed from your wishlist.<br>Please click <a href='http://eggcavity.com/edit-wishlist'>here</a> to return to the edit page.";
} else {
// Get current user's username
$current_user = wp_get_current_user();
$username = $current_user->user_login;
$theDeleteCount = 0;
// Just display the form
$sql = 'SELECT Creature, Picture, Stage, Gender, Frozen, ID FROM Wishlists WHERE Username = "' . $username . '"';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo '<form method="POST"><table><strong>' .
'<tr>' .
'<td></td>' .
'<td>Creature</td>' .
'<td>Stage</td>' .
'<td>Gender</td>' .
'<td>Frozen</td>' .
'</tr></strong>';
while($row = $result->fetch_assoc()) {
$creature = $row["Creature"];
$id = $row["ID"];
$picture = $row["Picture"];
$stage = $row["Stage"];
echo '<input name="ids[]" type="hidden" value="' . $id . '">' .
'<input name="' . $id . 'creature" type="hidden" value="' . $creature . '">' .
'<tr>' .
'<td rowspan="2"><img src="' . $picture . '"></td>' .
'<td>' . $creature . '</td>' .
'<td><select name="' . $id . 'stage">' .
'<option value ="' . $stage . '" selected>' . $stage . '</option>' .
'<option value = "Stage1">Stage1(Egg)</option>' .
'<option value = "Stage2">Stage2</option>' .
'<option value = "Stage3">Stage3</option>' .
'<option value = "Stage4">Stage4</option>' .
'</select></td>' .
'<td><select name="' . $id . 'gender">' .
'<option value ="' . $row["Gender"] . '" selected>' . $row["Gender"] . '</option>' .
'<option value = "Unspecified">Unspecified</option>' .
'<option value = "Female">Female</option>' .
'<option value = "Male">Male</option>' .
'</select></td>' .
'<td><select name="' . $id . 'frozen">' .
'<option value ="' . $row["Frozen"] . '" selected>' . $row["Frozen"] . '</option>' .
'<option value="Unspecified">Unspecified</option>' .
'<option value="Yes">Yes</option>' .
'<option value="No">No</option>' .
'</select></td>' .
'</tr>' .
'<tr>' .
'<td colspan="3">Notes: <input type="text" name="' . $id . 'notes" value="' . $row["Notes"] .'"></td>' .
'<td>' . 'Delete<br>' . '<input type="checkbox" name="creatures[]" value="' . $id . '"></td>' .
'</tr>';
}
echo '</table><input name="submit" type="submit" id="submit" value="Update"></form>';
} else {
echo "<br>You have no creatures in your wishlist.";
}
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
// Close the connection to the database
$conn->close();
If you could please help me find what is wrong with the information I am passing to the foreach() statement:
foreach($_POST['delete'] as $selected){
I would be forever grateful. Any idea helps.
I have tried a few many things, a lot of which were found on stackoverflow. I think I am probably missing something small and/or stupid. I have another page running off of a checkbox form which works just fine.
Thank you and have a great day!
The form element that contains the ids of cratures to be deleted is called creatures[] so you need to process the contents of that POST variable rather than delete - even though delete is what you wish to do. SO, perhaps something like this:-
Replace
$theCount = 0;
foreach($_POST['delete'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
with
$theCount = 0;
$creatures=!empty( $_POST['creatures'] ) ? $_POST['creatures'] : false;
if( $creatures ) {
if( !is_array( $creatures ) ) $creatures=explode(',',$creatures);
foreach( $creatures as $id ){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$theCount++;
}
}
if deleting is optional every time then just put an variable check like
if(isset($_POST['creatures']))
{
foreach($_POST['creatures'] as $selected){
$sql = "DELETE FROM Wishlists WHERE ID = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $selected);
$stmt->execute();
$theCount++;
}
}
this code will run only when it finds $_POST['creatures'] means ur checkbox is checked
Related
Here are a few functions that I am using:
function dp_find_results($table_name) {
global $wpdb;
$result = $wpdb->get_results ( "
SELECT *
FROM $table_name
WHERE role = 'member' OR role = 'admin'
" );
echo '<table><form action="" method="POST">';
foreach ( $result as $page )
{
if($page->role === 'member') {
$value1 = 'admin';
$value2 = 'Super Admin';
} elseif($page->role ==='admin') {
$value1 = 'member';
$value2 = 'Super Admin';
} else {
$value1 = 'member';
$value2 = 'admin';
}
echo
'<tr>
<th>Role</th>
<th>Username</th>
<th>Update</th>
</tr>';
echo '<tr>';
echo '<td>
<select name="role">
<option value="' . $page->role . '">' . $page->role . '</option>
<option value="' . $value1 . '">' . $value1 . '</option>
<option value="' . $value2 . '">' . $value2 . '</option>
</select>
</td>';
echo '<td>' . $page->username .'</td>';
echo '<td><button class="danzerpress-button-modern" type="submit" name="role-update-' . $page->username . '" value="' . $page->username . '">Update</button></td>';
echo '</tr>';
}
echo '</form></table>';
}
function get_registered_users() {
global $wpdb;
$table_name = 'dp_user_roles';
$result = $wpdb->get_results ( "
SELECT *
FROM $table_name
" );
$users = array();
foreach ($result as $arrayResult) {
array_push($users, 'role-update-' . $arrayResult->username);
}
//returns role-update-$username
return $users;
}
//checking for each registered user to match the button being posted
$variables = get_registered_users();
foreach($variables as $variable_name){
if(isset($_POST[$variable_name])){
$role = $_POST['role'];
$username = $_POST[$variable_name];
echo $role . '<br>' . $username . '<br>';
//after confirming submission is correct, update table
dp_change_user_role($role, $username);
}
}
function dp_change_user_role($role, $username) {
$table_name = 'dp_user_roles';
global $wpdb;
$wpdb->update( $table_name,
array(
'role' => $role
),
array(
'username' => $username )
);
}
Here it is in action
https://gyazo.com/62c0bdaca6a4c1443d011b8830d41130, the weird thing I am experiencing is that the bottom table row updates but the first table row will only change to the value the bottom table row is. I've tried a few things for trouble shooting but can't get my head around why it's not working. If I remove one of them then the changes work fine with no issues.
Here is another gif of the problem, here is what happens if I update the bottom one and then update the top one: https://gyazo.com/85956608dabe973ea8907b19daeb0094 very weird interaction and I can't figure out why it's doing it. This is the main issue unless you find others :).
I ended up figuring out what is was, $_POST['role'], was grabbing values from the other options and was not a unique identifier. So all the forms had options with the name="role". So added something unique so it would post correctly.
//checking for each registered user to match the button being posted
$variables = get_registered_users();
foreach($variables as $variable_name){
if(isset($_POST[$variable_name])){
//$role = $POST['role'] is wrong and needs to change
$role = $_POST['role'];
$username = $_POST[$variable_name];
echo $role . '<br>' . $username . '<br>';
//after confirming submission is correct, update table
dp_change_user_role($role, $username);
}
}
//This is where the role would need to change name="" to something that will identify it as unique
<select name="role">
<option value="' . $page->role . '">' . $page->role . '</option>
<option value="' . $value1 . '">' . $value1 . '</option>
<option value="' . $value2 . '">' . $value2 . '</option>
</select>
So this is a part from the administrator page.
After several modifications I came to this, which is the best I could get unfortunately:
<?php
$sql = "SELECT name
FROM users";
$result = mysqli_query($connection, $sql);
$users = array();
while ($row = mysqli_fetch_assoc($result))
{
$users[] = $row["name"];
}
echo ('</br><form action="" method="POST" style="display:inline!important"></br>
<select name="deleteUser">
<option value="' . $users[1] . '">' . $users[1] . '</option>' .
'<option value="' . $users[2] . '">' . $users[2] . '</option>' .
'<option value="' . $users[3] . '">' . $users[3] . '</option>' .
'<option value="' . $users[4] . '">' . $users[4] . '</option>' .
'<input class="w3-bar-item w3-button w3-hide-small w3-hover-green" type="submit" value="Delete" name="delete"></select></form>');
if (isset($_POST["delete"]))
{
$sql = "DELETE
FROM users
WHERE name = '" . $_POST["deleteUser"] . "'";
mysqli_query($connection, $sql);
}
?>
I tried to write a loop to generate the select options like this:
<?php
$sql = "SELECT name
FROM users";
$result = mysqli_query($connection, $sql);
$users = array();
while ($row = mysqli_fetch_assoc($result))
{
$users[] = $row["name"];
}
echo ('</br><form action="" method="POST" style="display:inline!important"></br>
<select name="deleteUser">');
for ($i = 0; $i < count($users); $i++)
{
echo('<option value="' . $users[$i] . '">' . $users[$i] . '</option>');
}
echo('<input class="w3-bar-item w3-button w3-hide-small w3-hover-green" type="submit" value="Delete"></select></form>');
if (isset($_POST["delete"]))
{
$sql = "DELETE
FROM users
WHERE name = '" . $_POST["deleteUser"] . "'";
mysqli_query($connection, $sql);
}
?>
But the browser doesn't render it(i.e Chrome), maybe because it just can't on portions? Like to wait for the loop to complete and then to end with the last part of the form.
Anyway, how could I make it work? Thanks mates...
Instead of using while loop you can use foreach this is where you can use foreach properly
Here is an example that might help you
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
foreach($rows as $val){
//Here populate your options like this
echo '<option> '.$val["name"].' </option'
}
Hope this will help you out :)
I am new to PHP and Mysql programming and I would like to know if I can access another database row when showing data in a form.
Here is the code:
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
$con = mysqli_connect($mysql_host, $mysql_user, $mysql_password, $mysql_database);
$result = mysqli_query($con, "SELECT * FROM Elev WHERE Clasa = '" . $_SESSION['clasa'] . "' ORDER BY Nume ASC ");
$result2 = mysqli_query($con, "SELECT * FROM M_Profesori WHERE ID = '" . $_SESSION['ID_p'] . "' ");
while ($row2 = mysqli_fetch_array($result2)) {
while ($row = mysqli_fetch_array($result)) {
echo "<select>
<option value='" . $row2["Materia"] . "'>" . $row2["Materia"] . "</option>
<option value='" . $row2["Materia"] . "'>" . $row2["Materia"] . "</option>
</select>";
}
}
In the second option (<option value='" . $row2[Materia] . "'>" . $row2[Materia] . "/option>) I would like to access the next database row, not this one. Is this possible?
If I've understood, you can try this:
$row2 = mysqli_fetch_array($result2);
foreach($row2 as $key => $value) {
...
<option value='" . $row2[$key+1][Materia] . "'>" . $value . "</option>
...
}
try this...
In adicional, look this:
You can use a template to build better codification. (site in portuguese)
http://raelcunha.com/template.php
http://raelcunha.com/packages/extra/template/pt-br/api/index.php
To clean and tidy-up my code, I want to add multiple tables with the fields:
id
title
description
keywords
link
but I also want them in sections so in MySql I want different tables with categories such as: "News", "Social Networking" and "Shopping", but how can I get that? This is my code:
<?php
if( count($terms) == 0){ // If no terms entered, stop.
echo "No Search Terms Entered.";
}else{
// connect
$connect = mysql_connect("XXX", "XXX", "YYY") or die('Couldn\'t connect to MySQL Server: ' . mysql_error());
mysql_select_db("theqlickcom_774575_db1", $connect ) or die('Couldn\'t Select the database: ' . mysql_error( $connect ));
/* Query Statement Building - Terms together */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
/* Query Statement Building - Terms Separate */
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " OR ";
}
$query .= "keywords LIKE '%{$each}%'";
}
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
} else {
echo "No results found for \"<b>{$k}</b>\"";
}
}
//disconnect
}
?>
If you have to search multiple table with one query
1.use mysqli
2.use UNION ALL in query
Join table
use mysql procedure
I recently modified some code to allow for my quiz.php script to accommodate multiple quizzes as opposed to just one. To do this I sent along the quiz_id and quiz_title variables when the user clicks the link for the quiz and I receive them using $_GET. However, once the quiz form is submitted the quiz_id column no longer updates in the high_score table.
Here is the code for quiz.php
<?php
// Start the session
require_once('startsession.php');
// Insert the Page Header
$page_title = "Quiz Time!";
require_once('header.php');
require_once('connectvars.php');
// Make sure user is logged in
if (!isset($_SESSION['user_id'])) {
echo '<p>Please log in to access this page.</p>';
exit();
}
// Show navigation menu
require_once('navmenu.php');
// Connect to database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Declare $quiz_id
$quiz_title = $_GET['title'];
$quiz_id = $_GET['id'];
// print_r($quiz_title);
// print_r($quiz_id);
// Grab list of question_id's for this quiz
$query = "SELECT question_id FROM question WHERE quiz_id = '" . $quiz_id . "'";
$data = mysqli_query($dbc, $query);
$questionIDs = array();
while ($row = mysqli_fetch_array($data)) {
array_push($questionIDs, $row['question_id']);
}
// Create empty responses in 'quiz_response' table
foreach ($questionIDs as $questionID) {
$query = "INSERT INTO quiz_response (user_id, question_id) VALUES ('" . $_SESSION['user_id'] . "', '" . $questionID . "')";
mysqli_query($dbc, $query);
}
// If form is submitted, update choice_id column of quiz_response table
if (isset($_POST['submit'])) {
// Inserting choices into the response table
foreach ($_POST as $choice_id => $choice) {
$query = "UPDATE quiz_response SET choice_id = '$choice', answer_time=NOW() " .
"WHERE response_id = '$choice_id'";
mysqli_query($dbc, $query);
}
// Update the 'is_correct' column
// Pull all is_correct data from question_choice table relating to specific response_id
$total_Qs = 0;
$correct_As = 0;
foreach ($_POST as $choice_id => $choice) {
$query = "SELECT qr.response_id, qr.choice_id, qc.is_correct " .
"FROM quiz_response AS qr " .
"INNER JOIN question_choice AS qc USING (choice_id) " .
"WHERE response_id = '$choice_id'";
$data=mysqli_query($dbc, $query);
// Update is_correct column in quiz_response table
while ($row = mysqli_fetch_array($data, MYSQLI_ASSOC)) {
$total_Qs ++;
if ($row['is_correct'] == 1) {
$query2 = "UPDATE quiz_response SET is_correct = '1' " .
"WHERE response_id = '$row[response_id]'";
mysqli_query($dbc, $query2);
$correct_As ++;
}
}
}
// Update high_score table with $correct_As
$quiz_id = $_POST['quiz_id'];
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
mysqli_query($dbc, $query);
// Display score after storing choices in database
echo 'You got ' . $correct_As . ' out of ' . $total_Qs . ' correct';
exit();
mysqli_close($dbc);
}
// Grab the question data from the database to generate the form
$Q_and_Cs = array();
foreach ($questionIDs as $questionID) {
$query = "SELECT qr.response_id AS r_id, qr.question_id, q.question " .
"FROM quiz_response AS qr " .
"INNER JOIN question AS q USING (question_id) " .
"WHERE qr.user_id = '" . $_SESSION['user_id'] . "' " .
"AND qr.question_id = '" . $questionID . "'";
$data = mysqli_query($dbc, $query)
or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");
// Store in $questions array, then push into $Q_and_Cs array
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
print_r($row);
$questions = array();
$questions['r_id'] = $row['r_id'];
$questions['question_id'] = $row['question_id'];
$questions['question'] = $row['question'];
// Pull up the choices for each question
$query2 = "SELECT choice_id, choice FROM question_choice " .
"WHERE question_id = '" . $row['question_id'] . "'";
$data2 = mysqli_query($dbc, $query2);
while ($row2 = mysqli_fetch_array($data2, MYSQL_NUM)) {
$questions[] = $row2[0];
$questions[] = $row2[1];
}
array_push($Q_and_Cs, $questions);
}
}
mysqli_close($dbc);
// Generate the quiz form by looping through the questions array
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
echo '<h2>' . $quiz_title . '</h2>';
$question_title = $Q_and_Cs[0]['question'];
echo '<label for="' . $Q_and_Cs[0]['r_id'] . '">' . $Q_and_Cs[0]['question'] . '</label><br />';
foreach ($Q_and_Cs as $Q_and_C) {
// Only start a new question if the question changes
if ($question_title != $Q_and_C['question']) {
$question_title = $Q_and_C['question'];
echo '<br /><label for="' . $Q_and_C['r_id'] . '">' . $Q_and_C['question'] . '</label><br />';
}
// Display the choices
// Choice #1
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[0] . '" />' . $Q_and_C[1] . '<br />';
// Choice#2
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[2] . '" />' . $Q_and_C[3] . '<br />';
// Choice #3
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[4] . '" />' . $Q_and_C[5] . '<br />';
// Choice #4
echo '<input type="radio" id="' . $Q_and_C['r_id'] . '" name="' . $Q_and_C['r_id'] . '" value="' . $Q_and_C[6] . '" />' . $Q_and_C[7] . '<br />';
}
echo '<br /><br />';
echo '<input type="hidden" name="quiz_id" value"'.$quiz_id.'" />';
echo '<input type="submit" value="Grade Me!" name="submit" />';
echo '</form>';
// echo 'Quiz_id: '.$quiz_id.'<br />';
// Insert the page footer
require_once('footer.php');
?>
Here is the code for quizlist.php
// Determine number of quizes based on title in quiz table
$query = "SELECT * FROM quiz";
$data = mysqli_query($dbc, $query);
// Loop through quiz titles and display links for each
while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
echo '' . $row['title'] . '<br />';
}
mysqli_close($dbc);
My problem has to do with the piece of code
$query = "INSERT INTO high_score " .
"VALUES ('0', '" . $_SESSION['user_id'] . "', '" . $quiz_id . "', '" . $correct_As . "', NOW())";
It works when I substitute a number (i.e. 2) in the place of $quiz_id, but in order for the script to work for different quizzes I need to be able to use a different quiz_id for different quizzes.
I'm having trouble taking the variable from quizlist.php using $_GET and then passing it along as a hidden value when the form is submitted. Am I doing something incorrect? Or am I missing something completely obvious? I'd appreciate any help! Thanks...
On the first clue, it seems to me that you're getting your $quiz_id form GET request (and that's correct), but you have a condition
if (isset($_POST['submit'])) {
which is fulfilled only when form is submitted (POST request), not link clicked. So all the code under this condition is not executed when you click the link