Ok, so I basically have an HTML form that consists of a hidden input and a submit button. When the button is pressed it will remove a specific row in my MySQL table. The code all actually does the function it should. However, I keep getting a syntax error displaying when I run it. Once I get the error, if I go back the row is gone, which is what I want. I am just not sure how to make it redirect after running like it should, rather than getting the error.
The error:
Error: 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 '1' at line 1
Line 1 seems fine to me (hence the confusion).
The PHP code that is running(campaignPostDelete.php):
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$postID = $_POST['postID'];
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=" . $postID);
if (!mysqli_query($con,$delete))
{
die('Error: ' . mysqli_error($con));
}
header("Location: index.php");
die();
mysqli_close($con);
?>
the HTML form with PHP in case it's needed:
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$campaignID = $_SESSION['campaignID'];
$result = mysqli_query($con,"SELECT posts.postID, posts.postDate, posts.postName, posts.postEntry FROM posts
INNER JOIN campaigns ON posts.campaignID= $campaignID
AND posts.campaignID= campaigns.campaignID ORDER BY postDate desc");
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "<form name='postDelete' action='campaignPostDelete.php' method='post'>
<input type='hidden' name='postID' value=" . $row['postID'] . ">
<input type='submit'>
</form>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
You are enclosing the ID in single quotes. It is an integer so shouldn't be enclosed in quotes.
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID='$postID'");
should be:
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=$postID");
However, you are also passing the connection string twice. So instead do this:
$delete = "DELETE FROM posts WHERE postID=$postID";
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
But this still leaves you vulnerable to SQL injection. Do at least this to improve this overall:
$delete = sprintf("DELETE FROM posts WHERE postID=%s", mysql_real_escape_string($postID));
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
You'll also want to sanitize your other inputs.
Related
management.php is the code which get information in php by a table.
And managementdel.php is the code which del the information.
I use mysql_fetch_array to show all data,and beside every information have a herf to delete
echo data in database.
When I del ,there no error inside.but database information haven't delete.
management.php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid=$row[0]'>get information</a></td><td>$row[0]</td><td><input type=text id='row1' name='row1' value='$row[1]' /></td>
<td>$row[2]</td><td>
<a href='searchtable.php?lid=$row[0]'>Change</a></td><td>
<a href='managementdel.php?lid=$row[0]'>Delete</a></td></tr>";
}
echo "</table>";
managementdel.php
<?php
$ac = $_GET['rowname'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>
There is so much stuff wrong with your script, I won't address it all. What I will do is answer your question that you asked which is: "Why it won't delete from database."
What is wrong in your script:
Using depreciated mysql_* library (See notes below)
Using meta refresh to redirect instead of something like header('Location: link');
Not sanitizing user input -> $_GET['lid'].
Posting user password in the table. (Hopefully not being stored as plaintext)
As stated, you're trying to get:
$_GET['rowname']
When you are sending lid -> managementdel.php?lid=$row[0]. You have to change that to:
$ac = $_GET['lid'];
NOTES
Please stay away from mysql_* functions as the library is depreciated.
Use either of the following two instead:
PDO
Mysqli Prepared Statements
And if you aren't going to do that, atleast try and sanitize your user inputs to prevent SQL Injections.
Using functions like intval() and mysql_real_escape_string() will help you but won't be as comprehensive as PDO/mysqli.
in managementdel.php file instead of
$ac = $_GET['rowname'];
there should be
$ac = $_GET['lid'];
Try
management.php
<?php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid= " . $row[0] . "'>get information</a></td><td>" . $row[0] . "</td><td><input type=text id='row1' name='row1' value='" . $row[1] . "' /></td>
<td>" . $row[2] . "</td><td>
<a href='searchtable.php?lid=" . $row[0] . "'>Change</a></td><td>
<a href='managementdel.php?lid=" . $row[0] . "'>Delete</a></td></tr>";
}
echo "</table>";
?>
managementdel.php
<?php
$ac = $_GET['lid'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>
I’m trying to retrieve the first 4 entries with a for loop, but it seems to repeat 1 entry 4 times.
This is my code:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten");
while($row = mysqli_fetch_array($result)) {
for ($result = 1; $result <= 4; $result++) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
}
mysqli_close($con);
You don't need a for loop. I've modified code, to retrive only first 4 items.
Look at the cahnged query LIMIT 4.
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
?>
You have a for loop inside the while loop. You can remove the for loop and use LIMIT from MySQL (which is better as fetching all entries by PHP (better performance), if you need only the first 4 entries):
SELECT * FROM activiteiten LIMIT 4
If you still want to do it with php:
$results = 0;
while($row = mysqli_fetch_array($result) && $results < 4) {
echo "<div class='agenda_item' style='background-color:#F39'>";
...
$results++;
}
Your code—as presented—mixes things up in ways that behave the way you see. The for loop is not needed. And you should set a LIMIT in your MySQL query like this:
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM activiteiten LIMIT 0,4");
while($row = mysqli_fetch_array($result)) {
echo "<div class='agenda_item' style='background-color:#F39'>";
echo "<img src='images/soosavond_small.jpg' class='soospict_small' />";
echo "<div class='agenda_content'>";
echo "<p class='datum'>" . $row['datum'] . "</p>";
echo "<p class='onderwerp'>" . $row['naam_activiteit'] . "</p>";
echo "<p class='details'>" . $row['beschrijving'] . "</p>";
echo "</div>";
echo "<a href='#'' class='pijlklein'>MEER INFO</a>";
echo "</div>";
}
mysqli_close($con);
The problem with your original code is mixing for with while ends up in the scenario you showed as explained in the PHP manual entry for while:
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE.
So you have a while iterating over the results, but then you also have for loop nested in there. 100% unnecessary.
The way I adjusted it is to just removed that for loop, but also add LIMIT 0,4 to the MySQL query. That basically tells MySQL to fetch 4 rows beginning from the first row which is referred to as 0.
So I am creating a blog for a school project, what I want to do is to be able the click on a blog post on the start page and be redirected to a separate page where only that blog post is displayed. What I have tried is this:
START PAGE LINK:
<a class="blog_title_link" href="singlepost?ID=' . $row['postID'] . '">
AND THE OTHER PAGE:
$pID = -1;
if ($_GET['ID'] != NULL) {
$pID = $_GET['ID'];
} else {
echo "ID failed.";
//Redirect to startpage...
}
$con = mysqli_connect("localhost","root","hejsan123","MyStrength");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM posts WHERE postID=") . $pID;
while($row = mysqli_fetch_array($result))
{
echo '<h1 class="blogTitle"><a class="blog_title_link">'
. $row['title'] . '</a></h1><img src="yo.jpg" /><p class="content_box_p">'
. $text . '</p>';
echo "<br>";
}
mysqli_close($con);
So I have the $pID to check if there actually is a ID, and then I try to get it from the URL
so that I can use it in the SQL to choose which information I want from the database.
What happens rigth now is
404 not found.
Hope you understand! Thanks!
the 404 Not Found error could it be because of the link:
<a class="blog_title_link" href="singlepost?ID=' . $row['postID'] . '">
__________^___
Maybe you need singlepost.php?ID...?
And then this line too should be:
$result = mysqli_query($con,"SELECT * FROM posts WHERE postID=" . $pID);
// ___not^___but^
I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
Basically I have edited the "new_topic" page in my generic forum so that the user can select the category of the post from a drop down list, rather than goto the category first and going to new topic, what I am trying to do now is when the thread is created, rather than jumping to the standard "your new thread was created here" it redirect to the category the topic was made under.
I tried using
header( "Location: category.php?id='. $topic_cat . '" );
But header was already being used elsewhere.
So I found a meta refresh that works to an extent..
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id='. $topic_cat .'>";
But it redirects to "category.phpid=" and outputs the following message..
The category could not be displayed, 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 8
Is there anyway I can make the page jump to the category that is only being defined in the submit function itself? Thanks for any help.
EDIT: would using "if" functions work to define the redirect? ie. if topic_cat 2 is selected in the form redirect to category.phpid=2??
Sorry I am very new to PHP and still trying to get my head around it all :(
Here is the topic creation page in it's entirety
<?php
//create_topic.php
include 'connect.php';
if($_SESSION['signed_in'] == false)
{
//the user is not signed in
echo 'Sorry, you have to be signed in to create a topic.';
}
else
{
//the user is signed in
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
//the query failed, uh-oh :-(
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['user_level'] == 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="">';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo '<textarea name="post_content" /></textarea><br /><br />
<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['post_content']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.<br /><br />' . 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['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=". $topic_cat ."'>";
}
}
}
}
}
; ?>
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=" . $topic_cat . "'>";
That should work. You needed to put double quotation-marks outside the . $topic_cat . variable like so; " . $topic_cat . "