I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;
Related
I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}
I'm at a complete loss here. I've written a relatively simple PHP script which updates a database record based on user input from a HTML form. The script contains an 'if' statement which executes based a hidden input. I know that the statement executes because the SQL query executes without a problem. The problem I'm having is that there there is another if statement within which should execute if the query object is set, but apparently it doesn't because the $message variable within is not assigned a value. I know that the query object is set because when I echo it it shows up as '1'. Below is the code block in question:
<?php
if(isset($_POST['submitted']) == 1) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
The echoes and print_r() below the query are for debugging purposes. The code that should echo $message is above the aforementioned code block (in my script) and looks like this:
<?php if(isset($message)) {echo $message;} ?>
Also, I tried using isset() for the $r variable and also changed the condition to $r !== false but that did not make a difference. When I just echo out $message without the isset() i get the obvious " Undefined variable: message in C:\xampp\htdocs\IMS\modify.php on line 47" error. My apologies if I'm missing something glaringly obvious. I did search beforehand but all the answers were too different from my situation and my knowledge of PHP is too small for me to be able to connect dots that are that far away, if you know what I mean.
EDIT: alright, I might as well put in the entire script. It's a bit all over the place, my apologies. The $id and $table variables do show as undefined after the submit button is pressed, could that have something to do with it?
<?php
error_reporting(E_ALL);
include('config/setup.php');
$id = $_GET['id'];
$table = $_GET['table'];
if ($table == "users") {
header('Location: index.php');
exit;
}
?>
<html>
<head>
<title>Update</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div class="back">
Back
</div>
<div class="panel">
<?php
if(!isset($_POST['submitted'])) {
$q = "SELECT name FROM $table WHERE id = $id";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_assoc($r);
if($table == "categories"){
$type = "category";
} else if ($table == "products") {
$type = "product";
}
echo "<p>You are changing the properties of this ".$type.": ".$row['name']."</p>";
}
?>
<?php if(isset($message)) {echo $message;} ?>
<form action="modify.php" method="POST">
<label for="name">New name</label>
<input type="text" class="form-control" id="name" name="name">
<button type="submit">Submit</button>
<input type="hidden" name="submitted" value="1">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="hidden" name="table" value="<?php echo $table; ?>">
</form>
<?php
if(isset($_POST['submitted'])) {
$name = mysqli_real_escape_string($dbc, $_POST['name']);
$q = "UPDATE ".$_POST['table']." SET name = '".$name."' WHERE id = ".$_POST['id'];
$r = mysqli_query($dbc, $q);
echo $r;
print_r($_POST);
echo mysqli_error($dbc);
if ($r !== false) {
$message = '<p>Operation executed successfuly</p>';
} else {
$message = '<p>Operation did not execute because: '.mysqli_error($dbc);
$message .= '<p>'.$q.'</p>';
}
}
?>
</div>
</body>
EDIT2: Alright, I came up with a "fix" that kind of solves the problem, namely, I moved the if condition up before the echo of $message and changed the condition to isset($_POST['submitted']. This will have to do, I suppose. I guess I should read up more about the order of operations when processing submitted data and parsing PHP files in general, because I am quite confused as to why this "fix" even works...
This (conditional) statement is a false positive:
if(isset($_POST['submitted']) == 1)
What you need to do is either break them up into two separate statements:
if(isset($_POST['submitted']) && $_POST['submitted']== 1)
or just remove the ==1.
Your code is also open to a serious SQL injection. Updating a table and setting columns from user input is not safe at all.
At best, use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
However, please note that you cannot bind a table and/or a column should you want to convert that to a prepared statement method.
Therefore the following will fail (when using a PDO prepared statement as an example):
$q = "UPDATE :table SET :name = :name WHERE id = :id;
or
$q = "UPDATE ? SET name = :name WHERE id = :id;
Read the following about this method, where that cannot be used:
Can I parameterize the table name in a prepared statement?
Can PHP PDO Statements accept the table or column name as parameter?
I have a table with registered users. My code is suppose to delete a row when clicking delete in the table.
This is in the database.php
.....
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr><td align="left">' . $row['Id'] . '</td><td align="left">Delete</td></tr>';
}
......
So, I'm getting the id when clicking delete. So far, this part works but when I tried to run the delete query it doesn't work.
delete.php
<?php
session_start();
include 'connection.php';
if (isset($_POST['Id']) && is_numeric($_POST['Id'])){
$id = mysqli_real_escape_string($conn, $_POST['Id']);
$result = mysqli_query("DELETE FROM table_name WHERE Id= '$id' ")
or die(mysqli_error());
echo "<h3><br><br><a href=database.php> <b> Go Back</a></h3>";
echo "Data Deleted";
}else {
echo "Error";
echo "<h3><br><br><a href=database.php> <b> Go Back</a></h3>";
}
?>
I just get "Error" and it doesn't remove the row. How can I fix it?
Edit:
<?php
session_start();
include 'connection.php';
if (isset($_GET['Id']) && is_numeric($_GET['Id']))
{
$id = mysqli_real_escape_string($conn, $_GET['Id']);
$result = mysqli_query("DELETE FROM User_reg WHERE Id= '$id' ")
or die(mysqli_error());
echo "<h3><br><br><a href=AdminLog.php> <b> Go Back</a></h3>";
echo "Data Deleted";
}else {
echo "Error";
echo "<h3><br><br><a href=AdminLog.php> <b> Go Back</a></h3>";
}
?>
Still getting the same result with the delete query not working.
Also "Id" name is set in the same way as in the database.
$_POST['Id'] is not set, because you got to that script via a link.
Delete
links are GET requests, not POST requests. So, $_GET['id'] (note that it is $_GET['id'] rather than $_GET['Id'] because you used id in your link) should be set, but it's not really safe to use a link to delete things to begin with.
There are various ways to get around this issue. One way is to have the delete link in your table direct you to a intermediate confirmation page that posts to the actual delete script.
it would not work because you are sending a get parameters and checking for post and note the comment above for prepared statement and also try not to use get to delete data because a programmer can easily change the id and delete another user info use post instead because it cant be tweaked that is why social use let me callm it ajax to delete, because a deleted cannot be retrieved unless you create an alternative so use POST METHOD instead change this
if (isset($_POST['id']) && is_numeric($_POST['id'])){
$id = mysqli_real_escape_string($conn, $_POST['id']);
to this
if (isset($_GET['id']) && is_numeric($_GET['id'])){
$id = mysqli_real_escape_string($conn, $_GET['id']);
This should work
Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.
I've scoured the web for a tutorial about this simple task, but to no avail. And so I turn to you helpful comrades. Here's what I need to do:
I have a MySQL database with an Events table. I need to create a PHP web page with a list of the Event titles, and each title must be a link to the full details of the Event. But I want to avoid having to create a static page for each event, primarily because I don't want the data entry volunteer to have to create these new pages. (Yes, I realize that static pages are more SEO friendly, but I need to forego that in this case for the sake of efficiency.)
I've seen PHP url syntax with something like this:
pagename.php?id=20
but I don't know how to make it work.
Any and all help greatly appreciated.
Thanks!
Kip
This is basic php. You would simply query the DB for the event details before the page headers are written and write the html accordingly.
The first thing I would ask you is if you know how to connect to your database. From there, you query based on the $_GET['id'] value and use the results to populate your html.
Not to be rude, but the question itself suggests you're new to PHP, right? So in order to provide a solution that works we might want to know just how far you got.
Also, you can rewrite your dynamic urls to appear like static ones using apache's mod_rewrite. It's probably a novice level thing if you're interested in "pretty" url's.
MODIFIED ANSWER:
In your loop you would use the id from the query result (assuming your primary key is id)...
while($field = mysql_fetch_array($result)) {
echo "<p class='date'>";
echo $field['month']." ".$field['day'].", ".$field['year'];
echo "</p>";
echo "<h3>";
echo ''.$field['event_name'].'';
echo "</h3>";
}
Then on somepage.php you would use the get var id to pull the relevant info...
$result = mysql_query("SELECT * FROM `calendar` WHERE `id` = '".mysql_real_escape_string($_GET['id'])."');
don't forget to look into mysql_real_escape_string() for cleaning entries.
It's wise to take extra care when you are using $_GETvariables, because them can be easily altered by a malicious user.
Following with the example, you could do:
$foo = (int)$_GET['id'];
So we are forcing here the cast of the variable to a integer so we are sure about the nature of the data, this is commonly used to avoid SQL injections.
lets say you have the php file test.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("db", $conn);
$id = $_GET['id'];
$sql = "select * from table where id = $id";
$result = mysql_query($sql, $conn);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[0];
$content = $row[1];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
a dynamic page would be something like that..
Here is the pertinent code for extracting a list of events in November from a table named calendar, with each event having a link to a page called event.php and with the event's id field appended to the end of the url:
$result = mysql_query("SELECT * FROM calendar WHERE sort_month='11'");
while($row = mysql_fetch_array($result))
{echo
"<a href='event.php?id=".$row['id']."'>".$row['event_name']."</a>"
;}
And here is the pertinent code on the event.php page. Note the row numbers in brackets depends on the placement of such in your table, remembering that the first row (field) would have the number 0 inside the brackets:
$id = $_GET['id'];
$sql = "select * from calendar where id = $id";
$result = mysql_query($sql, $con);
if ($result){
$row = mysql_fetch_row($result);
$title = $row[12];
$content = $row[7];
}
?>
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<h1><?php echo $title ?></h1>
<p><?php echo $content ?></p>
</body>
</html>
This works for me, thanks to the help from those above.
$foo=$_GET['id'];
in your example $foo would = 20