I am currently working on my assignment, I am trying to create a ban system for users, I wanna update the value of Deleted in my database to 1 whenever I press the submit button, I tried many on youtube videos but has not given any process
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
$row2 = mysqli_fetch_assoc($result);
if ($row2['Admin'] == 0) {
echo '<div class="alert alert-warning" role="alert">
Unfortunately you do not have access to this page
</div>';
}
else {
$query = " SELECT * FROM Users WHERE Admin = 0";
$result = mysqli_query($link, $query);
echo '<div class="container">';
echo '</div>';
echo '<div class="container"><table class="table table-primary table-hover">';
echo '<tr><th>' . 'NameID' . '</th><th>' . 'Name' . '</th><th>' . 'Email' . '</th><th>' . '</tr>';
while ($row2 = mysqli_fetch_assoc($result)) {
echo '<tr><td>' . $row2['UserID'] . ' </td><td> ' . $row2['FirstName'] . ' ' . $row2['LastName'] . ' </td><td> ' . $row2['EMail'] . ' </td><td> '
. '<input type="submit" name="submit" class="btn btn-primary btn-xs" value="BAN">' . ' </td></tr>';
}
if (isset($_POST['submit'])) {
echo '</table>' . '</div>';
$id = $_SESSION['UserID'];
$query = "SELECT * FROM Users WHERE UserID='$id'";
$result = mysqli_query($link, $query);
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
}
}
}
You define $query2 but never execute it. This is a common mistake.
Tip: Don't declare SQL as strings and then run it later, get in the habit of supplying the query as a direct argument to prepare().
For example:
$stmt = $link->prepare('UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID`=?');
$stmt->bind_param('i', $id);
$stmt->execute();
You don't run the $query2, do it like this
if ($_POST['submit']) {
$query2 = "UPDATE `Users` SET `Deleted` = '1' WHERE `Users`.`UserID` ='$id'";
mysqli_query($link, $query2);
}
Related
Friends, I show the field name as the value 1 of the database and the value as the result of the field, but I can not raise it to save the value of the field.
$result = $db->query($query);
while($rowID = $result->fetchArray() ){
echo
" <label class=\"control-label \" for=\"text\">
".$row['value1'] ."
</label>
<input class=\"form-control\" value=".$rowID['value2'] ." id=\"\" name=".$rowID['id']." type=\"text\"/>
</div>";
}
if( isset($_POST['submit_data']) ){
$ret1 = $db->query($query);
while($rowID = $ret1->fetchArray())
{
$query = "UPDATE table set value2 ='" . $_POST[$rowID['id']] . "' WHERE id='" . $rowID['id'] . "'";
}
if( $db->exec($query) ){
$message = "Data is updated successfully.";
}else{
$message = "Sorry, Data is not updated.";
}
}
Your last generated value in while loop will be value of $query. you should execute query at same time.
if( isset($_POST['submit_data']) ){
$ret1 = $db->query($query);
while($rowID = $ret1->fetchArray())
{
$query = "UPDATE table set value2 ='" . $_POST[$rowID['id']] . "' WHERE id='" . $rowID['id'] . "'";
if( $db->exec($query) ){
$message = "Data is updated successfully.";
}else{
$message = "Sorry, Data is not updated.";
}
}
}
I have a mysql table which I'm trying to turn into jQuery listview widgets. The part that I'm having trouble with is how best to extract the info from the table without doing multiple queries on the db itself. I have the following code which works:
global $conn;
$sql = "SELECT `id` FROM `implantFamilies` WHERE `familySelector` = '" . $_POST['implantFamily'] . "'"; //need to sanitise this
$result = $conn->query($sql);
if ($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
$familyId = $row["id"];
}
} else {
die("Error: " . $result->num_rows . " family groups in result. Alert administrator.");
}
?>
<form class="ui-filterable">
<input id="filterBasic-input" data-type="search">
</form>
<?php
$sql = "SELECT DISTINCT `familySection` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "'";
$sections = $conn->query($sql);
if ($sections->num_rows > 0) {
while ($sectionRow = $sections->fetch_assoc()) {
$output .= "<b>" . $sectionRow["familySection"] . "</b><br>";
//DISPLAY COLLAPSIBLE DIV HERE
$sql = "SELECT DISTINCT `sectionHeading` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "'";
$dividers = $conn->query($sql);
if ($dividers->num_rows > 0) {
while ($headingRow = $dividers->fetch_assoc()) {
$output .= "<i>" . $headingRow["sectionHeading"] . "</i><br>";
//DISPLAY list-divisers DIV HERE
$sql = "SELECT `reference`, `description`, `filterText`, `requiresLot` FROM `implants` WHERE `familyGroupId` = '" . $familyId . "' AND `familySection` = '" . $sectionRow["familySection"] . "' AND `sectionHeading` = '" . $headingRow["sectionHeading"] . "'";
$implants = $conn->query($sql);
if ($implants->num_rows > 0) {
while ($implantRow = $implants->fetch_assoc()) {
$output .= $implantRow["description"] . "<br>";
//DISPLAY implants DIV HERE
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
}
} else {
$output = "0 results";
}
$conn->close();
echo $output;
On the first lot of (simple) data which I've put into the table, this code executes 23 mysql queries. There must be a simpler way!
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
I am trying to remove a user from the mailing list right before I perform the emailing to my users. However, the code responsible for this within the second while loop is not executing.
Can somebody see why this is?
<?php
$query = "SELECT * FROM remove_request";
$result = mysqli_query($dbc,$query);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$query = "DELETE FROM mail_table WHERE first_name='" . $row["first_name"]
. "' AND last_name='" . $row["last_name"]
. "' AND email_address='" . $row["email_address"] . "'";
$result = mysqli_query($dbc,$query);
echo $row["first_name"] . ' has been removed from the mail list.';
}
}
$query = "SELECT * FROM mail_table";
$result = mysqli_query($dbc,$query) or die('Error querying database');
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
mail($row["email_address"],$subject,$message,$headers);
echo 'email sent to ' . $row["first_name"] . "\n";
}
}
mysqli_close($dbc);
?>
When I using the following code I cannot insert data. It shows the following error message:
[An error occured while inserting your data. Please try again later.You have an error in your SQL syntax: check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 10]
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['userid'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
`
You missed to add quotes around each string:
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
'" . mysql_real_escape_string($_POST['topic_cat']) . "',
'" . $_SESSION['userid'] . "'
)";
You have to add single quotes around your second mysql_real_escape_string. (And also around your $_SESSION['userid'] if it contains a string.)
<pre>
<?php
$con = mysql_connect( 'localhost', 'root','' );
if (!$con)
{
die( 'Could not connect: ' . mysql_error() );
}
mysql_select_db( "stack",$con );
$_SESSION['userlevel']= 1;
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['userlevel'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
$user =1;
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ", ". $user. "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",1
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
//after a lot of work, the query succeeded!
echo 'You have successfully created your new topic.';
}
}
}
}
?>
</pre>
i am using same script and it is working. please check your session if it creates
Your sql query is breaking here enclose your string and date values with "'"
VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "',
NOW(), <--- enclose with ."'"