I've updated the code but keep getting new errors.
I'm really hoping that someone can help me and look at my code to see what is wrong.
I have a database table on a webpage and I have one edit button and one delete button on each table row. At the moment I'm just trying to get the delete button to work and it will just not delete the row in the database even though I selected that ID. It looks like it's picking up the correct ID.
Can someone tell what is wrong? Below is the code...
<?php
require 'connect.inc.php';
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = get_post('id');
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
if (!mysql_query($query, $db_server))
echo "DELETE failed: $query<br>".
mysql_error() . "<br><br>";
}
$query = "SELECT * FROM movies, categories WHERE movies.genre_id = categories.genre_id";
$result = mysql_query($query);
if (!$result) die ("Database access failed:" .mysql_error()) ;
$rows = mysql_num_rows($result);
echo '<table><tr><th>Title</th><th>Release year</th><th>Genre</th><th>Director</th><th>Update</th><th>Delete</th></tr>';
for ($j = 0 ; $j < $rows ; ++$j) {
$row = mysql_fetch_row($result);
//$id = $row[0];
echo '<tr><td>' .$row[1] . '</td>' ;
echo '<td>' .$row[2] . '</td>' ;
echo '<td>' .$row[3] . '</td>' ;
echo '<td>' .$row[4] . '</td>' ;
echo '<td>'."<a href='edit_movie.php?edit=" . $row[0] . "'>Edit</a>".'</td>';
echo '<td><form action="index.php" method="POST">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name="id" value="'. $row[0] .'" />
<input type="submit" value="Delete" /></form>
</td></tr>' ;
}
echo '</table>';
include 'add_movie.php';
?>
You forget to close action attribute.
You have echo '<td><form action="index.php method="POST"> change it to
echo '<td><form action="index.php" method="POST">
Just to be clear: 'mysql_query' and accompanying commands is deprecated and should really not be used. The OP however stated that it was required for an assignment. The easiest way to replace them is to use 'mysqli_*' instead. For an example using parameter binding to avoid sql-injection:
http://www.php.net/manual/en/mysqli-stmt.bind-param.php
Shouldn't it be:
if (isset($_POST['delete']) && isset($_POST['id'])) {
$id = mysql_real_escape_string($_POST['id']);
...
See this link for some info on 'get_post':
PHP: Having a problem with get_post
The problem there was that the function 'get_post' was defined on the next page of the course literature, wich the asker hadn't noticed.
The variable $_POST['id'] contains the id-value sent from a form via an HTTP POST-request. You check if that value is set, and then you should assign it to '$id' like i wrote.
Your delete sql has wrong quotes
$query = "DELETE FROM movies WHERE id='.$id.' LIMIT 1";
change to either
$query = "DELETE FROM movies WHERE id=".$id." LIMIT 1";
or
$query = "DELETE FROM movies WHERE id=$id LIMIT 1";
Try changing the form action
'<td><form action="index.php" method="POST">
Also check your database connection is properly established
Perhaps this might help for get_post
PHP: Having a problem with get_post
Related
My aim is to create a dynamic webpage that returns all of the records in a table meeting a given criteria and uses them to populate a webform. The user can then make changes as they wish and update the entire table with a single button press.
In the example below I'd like to list all the events, the start time will appear in an editable text box and when I press submit it should update all the values.
I've created a mock-up below:
$query = "SELECT * FROM Events";
$result = mysqli_query( $dbc, $query ) ;
if ( mysqli_num_rows( $result ) > 0 )
{
echo '<form action="update_events.php" method="post">>';
echo '<table><tr>';
while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ))
{
echo '<td>' . $row['Event_Name'] .' </td>'.
'<td>' . $row['Event_Date'] .'</td>'.
'<td><input name="'. $row['Event_ID'] .'" type="text" value="'$row['Event_Start_Time'] .'"></td>';
echo '</tr>';
}
echo '</table>';
echo ' <input type="submit" value="Submit"></form>';
mysqli_close( $dbc ) ;
}
else
{
echo '<p>There are currently no events.</p>' ;
}
I cannot figure our how to get the processing on the update_events.php to work, any help would be appreciated.
foreach(????){
$sql = "UPDATE Events SET Event_Start='$Event_Start' WHERE id='$Event_ID'";
mysqli_query($dbc, $sql)
}
You really want to keep your POST variables static, it makes life easier. Don't try and use one variable to store two values, give them one each.
As you are submitting multiple values to the server which you want to loop over then it makes sense to submit them in arrays, so something like this:
$i=0;
while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ))
{
echo '<td>' . $row['Event_Name'] .' </td>'.
'<td>' . $row['Event_Date'] .'</td>'.
'<td><input name="event['.$i.'][start]" type="text" value="'$row['Event_Start_Time'] .'"><input name="event['.$i.'][ID]" type="hidden" value="'. $row['Event_ID'] .'"></td>';
echo '</tr>';
$i++;
}
Now your form will submit all the events as a multidimensional array which you can retrieve in $_POST['event'] and loop over it to do your database updates like this:
$stmt = $this->mysqli->prepare("UPDATE Events SET Event_Start=? WHERE id=?");
$stmt->bind_param('ss', $start, $id);
foreach ($_POST['event'] as $event) {
$start = $event['start'];
$id = $event['ID'];
$stmt->execute();
}
This code uses a prepared statement for the database insert, the method you are using is insecure and leaves you vulnerable to SQL injection. You should read up on Mysqli prepared statements and start using them.
Okay so I'm making php that will pull every entry from a data base that matches the name you put in a textbox. so here is a image of the database
http://i.stack.imgur.com/LvmrM.png < screen shot of database
So if i where to put "DigitalNuke" in the textbox and hit the submit button I want only the rows that have "DigitalNuke" as the value in the second column "referrer"
<form ACTION="" METHOD=post>
<div class="input-append">
<input class="span2" id="youruser" type="text" name="youruser" placeholder="Your Username">
<button class="btn btn-success" type="submit">Retrive</button>
</div>
</form>
<?php
require_once 'connect.php';
$name = isset($_POST['youruser']);
$conn= mysqli_connect ($dbhost,$dbuser,$dbpass,$dbname)or die(mysqli_error());
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
$result = mysqli_query($conn, $query1)
or die('Error querying the database: ');
echo '<table class="table table-bordered">';
echo '<caption>Your Referred Members</caption>' . '<thead><tr><th>ID</th>' . '<th>Username</th>' . '<th>Brigade</th>' . '<th>Faction</th>' . '<th>Activity</th>' . '</tr></thead>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr class='success'><td>" . $row['id'] . "</td><td>" . $row['username'] . "</td><td>" . $row['brigade'] . "</td><td>" . $row['faction'] . "</td><td>" . $row['activity'] ."</td></tr>";
}
?>
So as of now it doesn't do anything when I hit the submit button. Well it kind of works, except for instead of pulling the data from the table, it just puts id, username, brigade, faction, activity in each row of the generated table.
http://i.stack.imgur.com/XF71h.png < screen shot
Any help would be appreciated, if you need anything else let me know and i'll post it.
$query1 = "SELECT 'id', 'referrer', 'username', 'brigade', 'faction', 'activity' FROM refmems WHERE referrer='$name";
should be:
$query1 = "SELECT `id`, `referrer`, `username`, `brigade`, `faction`, `activity` FROM refmems WHERE referrer='$name'";
Also learn how to use prepared statements for MySQLi. Your code is open to SQL injection.
Your syntax is broken.
"SELECT id, referrer, username, brigade, faction, activity FROM refmems WHERE referrer='$name"
There is no closing single quote after $name, and the fields don't get quoted (or use backticks but it isn't necessary).
Also, you are asking for trouble. You've got user input with no validation/sanitization.
I'm trying to allow a user to accept/decline requests for an event through submit buttons. Information is looped and displayed in a row (username, location, accept,decline).
Right now 2 users are being displayed; User 1 and User 2(current ones for testing). Anyway, I'm trying to get the correct userid to work with the correct username. Currently, regardless of which user I accept or decline, user 2 is displayed. I tried to set the value of the userid based on a hidden input but it's not working correctly.
Here is my code.
for($i=0;$i<count($userExplode)-1;$i++){
$user = mysql_query("select userid,username from users where userid = ".$userExplode[$i]." ");
$user = mysql_fetch_array($user);
$userLoc = mysql_query("select userLocation from userinfo where userid = ".$userExplode[$i]." ");
$location = mysql_fetch_array($userLoc);
$locationExplode = explode("~",$location['userLocation']);
//the displayed output is working correctly so I know it's setting $user['userid'] properly
echo '<form method="post"><table><tr><td>' . $user['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td><input type="hidden" name="userReq" value='.$user['userid'].'></td>
<td><input type="submit" name="accept" value="Accept Request" ></td>
<td><input type="submit" name="decline" value="Decline Request" ></td></tr>';
}
echo '</table></form>';
}
if(isset($_POST['accept'])){
echo $_POST['userReq']; //displays user 2 even if I click user 1
}
if(isset($_POST['decline'])){
echo $_POST['userReq']; //also displays user 2 even if i click user 1
}
}
There is a lot wrong with your code:
You don't close the for's in the loop
there is no action on your form
you're starting a new table for each loop
Replace the submit button's by anchors and add the parameters in there. Then you can style the anchor to look like a button.
<input type="submit" name="decline" value="Decline Request" >
becomes
echo "Decline request";
Remove all the <form>s and load everything in 1 table.
Result:
<?php
if(isset($_GET['action']) AND isset($_GET['userid'])){
switch($_GET['action']){
case "accept":
// do whatever
break;
case "decline":
// do whatever
break;
default:
die('something wrong');
break;
}
}
echo '<table width="100%">';
for($i=0; $i <= count($userExplode); $i++){
$q = "
SELECT u.userid,u.username, userLocation
FROM users u
INNER JOIN userLocation ul ON u.userid = ul.userid
WHERE u.userid = ".$userExplode[$i]."
";
$rs = mysql_query($q) or die(mysql_error());
$user = mysql_fetch_array($rs);
$locationExplode = explode("~",$user['userLocation']);
//the displayed output is working correctly so I know it's setting $user['userid'] properly
echo '<tr><td>' . $user['username'] . '</td>'.
'<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>'.
'<td>Accept Request</td>'.
'<td>Decline Request</td></tr>';
}
echo '</table>';
I think this is only the tip of the iceberg.. How do you get $userExplode for example? It is very weird and illogical. I assume that you first run a query to get all the users and then loop with this for?
In your example it looks like you have some code issues. Here it is cleaned up a little:
for($i=0;$i<count($userExplode)-1;$i++) {
$user = mysql_query("select userid,username from users where userid = ".$userExplode[$i]." LIMIT 1");
$user = mysql_fetch_array($user);
$userLoc = mysql_query("select userLocation from userinfo where userid = ".$userExplode[$i]." LIMIT 1");
$location = mysql_fetch_array($userLoc);
$locationExplode = explode("~",$location['userLocation']);
echo '<form method="post" action=""><table><tr><td>' . $user['username'] . '</td>
<td>' . $locationExplode[0] . ', ' . $locationExplode[1] . '</td>
<td><input type="hidden" name="userReq" value='.$user['userid'].'></td>
<td><input type="submit" name="accept" value="Accept Request" ></td>
<td><input type="submit" name="decline" value="Decline Request" ></td></tr>';
echo '</table></form>';
}
if(isset($_POST['accept'])){
echo $_POST['userReq']; //displays user 2 even if I click user 1
}
if(isset($_POST['decline'])){
echo $_POST['userReq']; //also displays user 2 even if i click user 1
}
Based on your code, the array that's being passed should be:
$users = "1|2";
$userExplode=explode("|",$users) // or whatever your delimiter is
To test, do a var_dump($userExplode); prior to starting your loop to make sure you've exploded the entries going it.
A source dump of the original page would be helpful as well. If you could post that then I could see how your code is rendering the html form.
I'm pretty new to php, and for that matter server scripting in general (so go easy on me)
But regardless of that I managed to create this, the first half of a comment system:
<html>
<body>
<form name="Comment" action="InsertComment.php" method="POST">
Name: <input type="text" name="name" /><br>
Comment: <br><textarea style="height: 100px; width: 600px;" name="comment"></textarea><br>
<input id="Special_ID" name="id" value="<?php $unixtime = time(); echo $unixtime; ?>">
<!--^Gathers a unique id^-->
<input type="submit" />
</form>
</body>
</html>
Once submitted -->
<?php
$con = mysql_connect("Blaa", "Blaa", "Blaa");
if(!$con) {
die('Could not connect ' . mysql_error());
}
sql_select_db("Comments", $con);
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('$_POST[name]', '$_POST[comment]', '$_POST[id]')";
?>
This is exactly what I wanted, a user puts in their name, a comment, and a unique post id (time stamp) is generated, then it is all sent to mysql.
But now I'm dumb found as to how I can post this to another page..
I assumed something like:
if(ID == [the id of that post]) {
//$_GET the mysql stuff
//Post inside a specially made div or something
}
Along the lines of that, but I have no clue how to put that into practise :/
Any ideas?
Oh and Please don't suggest an echo type post, I've done that and it's not at all what I want.
**Also this is just the basic code, I don't need suggestions on how to touch it up just yet, also errors in this is only due to my sleep deprivation, the code does work.
As #Marc B has said, you'll first want to fix your SQL injection holes using mysql_real_escape_string. Change your insert statement to
$sql = "INSERT INTO Posts (Name, Comment, ID)
VALUES('" . mysql_real_escape_string($_POST['name']) . "', '" . mysql_real_escape_string($_POST['comment']) . "', '" . mysql_real_escape_string($_POST['id']) . "')";
To display your comment, try this
$sql = "SELECT Name, Comment, ID
FROM Posts
WHERE ID = '" . mysql_real_escape_string($_GET['PostID']) . "'";
$query = mysql_query($sql);
echo "<div id=\"comments_container\">";
while ($row = mysql_fetch_assoc($query))
{
echo "<div class=\"comment\">";
echo "<div class=\"name\">" . $row['Name'] . "</div>";
echo "<div class=\"comment_body\">" . $row['Comment'] . "</div>";
echo "</div>"
}
echo "</div>";
Then CSS style your DIVs using IDs and classes.
Just an example using mysql_fetch_object
Please sanitize your $_GET data before inserting to MySQL, this is a huge injection security flaw.
$sql = "SELECT * FROM Posts WHERE id={$id}"
$result = mysql_query($sql);
$obj = mysql_fetch_object($result)
if(is_object($obj))
{
echo "Welcome " . $obj->Name;
}
A full length example is given here:
http://manzur-ashraf.com/code/auto_commenting_system/Automatic_Commenting_System_and_Email_notification_using_PHP_and_MYSQL.htm
In addition to using a MYSQL database to store the comments, you can also post email to the admin about new comments.
I am trying to dynamically create php check-boxes linked to an MSSQL-Database. The idea is to List every item in the table, with a check box. From there the user will be able to check the check-boxes and click submit to change the value in 1 field of the Database to "A". I have the database linked to the php and It outputs the check-checkboxes and table values, however I do not know from there how to dynamically check the check-boxes to see if they are checked, or to use it from there.
This is roughly the approach you want to take to dynamically create checkboxes. There are of course prettier ways to accomplish this (i.e. Smarty templates).
<html>
...
<form method="post" action="submit.php">
<?php
// connect to DB here
$result = mysql_query("SELECT l.id, l.name, u.checked FROM List l LEFT JOIN UserAnswers u ON l.id = u.list_id WHERE u.user_id = 5");
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="cb_' . $row['id'] . '" ' .
'id="cb_' . $row['id'] . '" ';
if($row['checked'])
echo 'checked';
echo " />\n"
echo '<label for="cb_' . $row['id'] . '">' . $row['name'] . "</label><br />\n";
}
?>
<input type="submit" value="Submit" />
</form>
...
</html>
submit.php is a bit trickier. When a checkbox is checked, it will set a post item. However if it's unchecked, you won't get ANYTHING back, so you need to check your database for all the items you'll be expecting.
<?php
// connect to DB here
$result = mysql_query("SELECT id, name, checked FROM things");
$answers = Array();
while ($row = mysql_fetch_assoc($result))
{
$checked = isset($_POST['cb_' + $row['id']]);
$answers[$row['id']] = $checked;
}
// update your database here using $answers
foreach ($answers as $id => $checked)
{
$query = "REPLACE INTO UserAnswers SET user_id=5, list_id=" . $id . ", checked=";
if($checked)
$query .= "1";
else
$query .= "0";
mysql_query($query);
}
This is all off the top of my head, there are better ways to do most of this. It's just a general direction. I make no guarantees about any of this. Oh and it looks quite vulnerable to SQL injection, watch out for that.