I'm taking a PHP course, using the Head First PHP and MYSQL textbook. The book was written back in 2008 so I am constantly wondering if what I'm learning is up to date.
The text book shows a self-referencing html form in php comments like this:
<?php
require_once('appvars.php');
require_once('connectvars.php');
if (isset($_GET['id']) && isset($_GET['date']) && isset($_GET['name']) && isset($_GET['score']) && isset($_GET['screenshot'])) {
// Grab the score data from the Get
$id = $_GET['id'];
$date = $_GET['date'];
$name = $_GET['name'];
$score = $_GET['score'];
$screenshot = $_GET['screenshot'];
}
else if (isset($_POST['id']) && isset($_POST['name']) && isset($_POST['score'])) {
// Grab the score data from the POST
$id = $_POST['id'];
$name = $_POST['name'];
$score = $_POST['score'];
}
else {
echo '<p class="error">Sorry, no high score was specified for removal.</p>';
}
if (isset($_POST['submit'])) {
if ($_POST['confirm'] == 'Yes') {
// Delete the screen shot image file from the server
#unlink(GW_UPLOADPATH . $screenshot);
//Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Delete the score data from the database
$query = "DELETE FROM guitarwars WHERE id = $id LIMIT 1";
$data = mysqli_query($dbc, $query)
or die('Unable to complete query');
mysqli_close($dbc);
// Confirm success with the user
echo '<p>The high score of ' . $score . ' for ' . $name . ' was succesfully removed.';
}
else {
echo '<p class="error">The high score was not removed.</p>';
}
}
else if (isset($id) && isset($name) && isset($date) &&
isset($score) && isset($screenshot)) {
echo '<p>Are you sure you want to delete the following high score?</p>';
echo '<p><strong>Name: </strong>' . $name . '<br><strong>Date: </strong>' . $date .
'<br><strong>Score: </strong>' . $score . '</p>';
echo '<form method="post" action="removescore.php">';
echo '<input type="radio" name="confirm" value="Yes">Yes ';
echo '<input type="radio" name="confirm" value="No" checked="checked">No ';
echo '<input type="submit" value="Submit" name="submit">';
echo '<input type="hidden" name="id" value="' . $id . '">';
echo '<input type="hidden" name="score" value="' . $score . '">';
echo '<input type="hidden" name="screenshot" value="' . $screenshot . '">';
echo '</form>';
}
echo '<p><< Back to admin page</p>';
?>
I kept getting an error message saying that my id variable is undefined. After doing some research, I removed the text inside of the action quotes. Now it works, but I'm still wondering why the book teaches this way. Are they both valid options?
A variable is echoed without quotes, so if you mix it with regular HTML code, you use the quotes for the HTML code, then end that with another quote of the same type - in your case a single quote.
But since the HTML code has to contain quotes (for the "value" attribute), you can mix single and double quotes as you did it.
The single quote before the variable ends the HTML echoing, the dot allows to connect a variable, after the variable a dot does the same, and then again single quotes for the HTML code.
Related
Below I have code that is supposed to update an entry in the database. When I click the submit button the form goes away but it is not replaced with anything and more importantly it doesn't update the database. I cannot seem to find where the error is and any help would be greatly appreciated.
<?php
define('TITLE', 'Quotes Entry!');
// Include the header:
include('header.php');
include('mysqli_connect.php');
// Leave the PHP section to display lots of HTML:
?>
<?php //
mysqli_set_charset($dbc, 'utf8');
if (isset($_GET['id']) && is_numeric($_GET['id']) ) { // Display the entry in a form:
// Define the query:
$query = "SELECT title, entry FROM Salinger WHERE entry_id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) { // Run the query.
$row = mysqli_fetch_array($r); // Retrieve the information.
//make the form
print '<form action = "edit_entry.php" method = "post">
<p> Entry Titles <input type= "text" name = "title" size = "40" maxsize = "100" value = "' . htmlentities($row['title']) . '" /></p>
<p>Entry Text <textarea name = "entry" cols = "40" rows = "5">'. htmlentities($row['entry']).'</textarea></p>
<input type = "hidden" name = "id" value = "'.$_GET['id'] .'" />
<input type = "submit" name = "submit" value = "Update This Entry!" />
</form>';
} else { // Couldn't get the information.
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) { // Handle the form.
$problem = "false";
if(!empty($_POST['title']) && !empty($_POST['entry'])){
$title = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['title'])));
$entry = mysqli_real_escape_string($dbc, trim(strip_tags($_POST['entry'])));
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
$problem = true;
}
if(!problem){
$query = "UPDATE Salinger SET title = '$title', entry = '$entry' WHERE entry_id = {$_POST['id']}";
$r = mysqli_query($dbc, $query); //execute the query
if(mysqli_affected_rows($dbc) == 1){
print'<p> The blog entry has been updated.</p>';
// Report on the result:
} else {
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
}
} else{
print '<p style="color: red;">Could not retrieve the blog entry because:<br />' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
mysqli_close($dbc); // Close the database connection.
include('footer.php'); // Need the footer.
?>
Because you set $problem = "false"; you need to set it to $problem= false;
"false" is not false
And !problem should be !$problem
You have a problem with GET[id].
It's getting blank cause of POST event on screen, due to which your SQL is not finding the record.
To test assign hard coded value in your select statement.
Example
$query = "SELECT title, entry FROM Salinger WHERE entry_id=10";
A php/mySQL booking function that's been working well suddenly stopped inserting booking entries into the database, with no changes to the code and a functioning database connection.
I run a parallel version of the page that is working on another website; the only difference between the two is that the broken version is running on php 5.6, the functioning one is still on 5.4.
Adding an error log brings no results even though the table doesn't update and I can't see any deprecated statements between php 5.4 and 5.6.
Can anyone spot the problem I'm missing?
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach ($_POST['class_id'] as $classes) {
$class_id = (int)$classes;
//UPDATE the bookings table **THIS PART IS NOT WORKING**:
$query = "INSERT INTO bookings (user_id, booking_name, class_id, time_stamp) VALUES ('$user_id', '$username', '$class_id', NOW())";
mysqli_query($dbc, $query);
}
foreach($_POST['class_id'] as $classes){
$class_id = (int)$classes;
//Change the booking numbers **THIS WORKS FINE**:
$increase = "UPDATE classes SET online_bookings = (online_bookings + 1), total_bookings = (total_bookings + 1), free_spaces = (free_spaces - 1) WHERE class_id = $class_id";
mysqli_query($dbc, $increase);
}
mysqli_close($dbc);
..and the table that provides the $_POST data:
echo'<div class="container">';
echo'<div class="span8 offset1 well">';
echo'<p class="lead text-info">Do you want to reserve space at these classes?</p>';
//table header
echo '<table id="dancers" class="table table-bordered table-hover">';
echo '<thead><tr><th>Date</th><th>Time</th><th>Venue</th><th>Who\'s going?</th></tr></thead>';
//create the form
echo '<form id="makebkg" method="post" action="' . $_SERVER['PHP_SELF'] . '">';
//Get the class IDs from the GET to use in the POST
foreach ($_GET['sesh'] as $class_id) {
$sql = "SELECT class_id, DATE_FORMAT(date, '%a, %d %b') AS new_date, DATE_FORMAT(time, '%H:%i') AS new_time, venue FROM classes WHERE class_id = '$class_id'";
$data = mysqli_query($dbc, $sql);
//get table data
while ($row = mysqli_fetch_array($data)) {
$date = $row["new_date"];
$time = $row["new_time"];
$venue = $row["venue"];
$class_id = $row["class_id"];
}
//Show a table of the selected classes
echo '<tr><td>' . $date . '</td>';
echo '<td>' . $time . '</td>';
echo '<td>' . $venue . '</td>';
echo '<td>' . $username . '</td></tr>';
echo '<input type="hidden" name="date[]" value="' . $date . '" />';
echo '<input type="hidden" name="time[]" value="' . $time . '" />';
echo '<input type="hidden" name="venue[]" value="' . $venue. '" />';
echo '<input type="hidden" name="username[]" value="' . $username . '" />';
echo '<input type="hidden" name="class_id[]" value="' . $class_id . '" />';
}
echo'</table>';
//Go Back button
echo '<a class="btn btn-link pull-left" href="classes.php"><i class="icon-arrow-left"></i> Go back</a>';
// Make booking button - LIVE
echo'<div id="confirmbtn">';
echo '<input type="submit" id="confirm" name="submit" class="btn btn-large btn-primary pull-right" value="Confirm">';
echo '</div>';
OK, I finally fixed the problem.
It turns out that the hosting company had changed the MySQL mode to 'strict'.
The INSERT statement here left some table columns blank and strict mode rejects the entire insert as a result. Changing the mode right before the insert command was a quicker way to get around the problem than updating the insert command:
// TURN OFF STRICT MYSQL MODE
$strict = "SET sql_mode = ''";
mysqli_query($dbc, $strict);
Thanks for all the advice and tolerance of an indolent coder.
Did you try to check your query?
error_reporting(1);
$q = mysqli_query($dbc, $query);
if (!$q)
{
echo 'Error' . mysqli_error($dbc);
}
Do same for other query.
Dear friends i am not an expert in php and need your help to solve an issue.
I am trying to create a page where i can call data from MySql and can edit/update it. The first part to display the data is done but i am unable to update it ... friends kindly help me solve this.
function Get_pages($mysql) {
$PageQuery = $mysql->query("SELECT * FROM pages WHERE PageID = '$pageID'");
while (($row = $PageQuery->fetch_assoc()) !== null)
{
echo '<form action="page.php" method="post">';
echo '<span class="lbl">Page Title</span>';
echo '<input name="PageTitle" type="text" value="' . $row["PageTitle"] . '" />';
echo '<span class="lbl">Page Content</span>';
echo '<textarea class="txt-area" name="PageContent" cols="" rows="18">' . $row["PageContent"] . '</textarea>';
echo '<input name="UpdateBtn" value="Update Page" type="submit" class="submit_btn"></form>';
}
// WHEN BUTTON CLICKED
if ($_REQUEST['UpdateBtn'])
{
$pageID = $_REQUEST["$pageID"];
$PageTitle = addslashes($_REQUEST['PageTitle']);
$PageContent = addslashes($_REQUEST['PageContent']);
$sql = mysql_query ("UPDATE pages SET PageTitle='$PageTitle', PageContent='$PageContent' WHERE pageID='$pageID'") or die ("Not Updating");
}
}
$sql = mysql_query ("UPDATE
should be
$sql = $mysql->query("UPDATE
You are making connection with mysqli_* function and using mysql_* function for update , because of that your UPDATE is failing.
I've checked my code compared with code elsewhere on my site and I can't see any inconsistencies, but for some reason the records are entering my database with blank data, here is my code.
<?php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
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 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>' . $row['sub_cat_name'] . '</b> has been added under the main category <b>' . $row['cat_name'] . '</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
}
}
; ?>
My categories table is structured like so..
cat_id
cat_desc
My subcategories table is structured like so..
id(AI)
c_id
sub_cat_name
sub_desc
If I haven't provided enough information please let me know.
You don't appear to be reading the $POST variables into the variables you're using in your query. You probably want something like this:
$sub_cat_name = mysql_real_escape_string($_POST['sub_cat_name']);
// repeat for other variables.
It seems to me that $cat_id $sub_cat_name and $sub_desc are not defined anywhere.
Also, you're missing a pipe here:
if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
// --------------------------------^
Lastly, I should note that the mysql_* functions are deprecated. You should really be using mysqli or PDO.
if($_SESSION['signed_in'] == false || $_SESSION['user_level'] != 1 )
------------------------------------^ (OR)
I also don't see where you set the variables. ('" . $cat_id . "' and etc...)
You should store them into a variable like so:
$cat_id = mysql_real_escape_string($_POST['name_of_the_input']); //and etc..
Or in your insert query do this: (Depending on the values whether or not you need to escape it like above)
'".$_POST['name_of_input']."',
so this was working perfect up until an hour ago and since then i have racked my brain to fix it and got nothing, maybe im missing the obvious (thats usually the case).
The code prints out a list of users and a button to ban them in a table, however the problem is if you click ban on say.. the 34th user it bans the first, then if you click ban on the 56th user it bans the second user. If you see my code you should see that that shouldn't be the case (note all other details are perfectly right except for the uID):
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="name" value="" />
<a onclick="document.getElementById(\'unban\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
The issue is in the action="unban.php?uid='.$uID.' as when i trace the path the id is always the lowest number (top result)
ban.php
<?php
include '../../includes/dataBase.class.php';
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['uid'])){
header("Location: users.php?action=1");
}
$uid = $_GET['uid'];
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('$ip')")or die(mysql_error());
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '$uid'")or die(mysql_error());
//header("Location: users.php?action=1");
echo $uid;
?>
You provide a form for each user which bans/unbans that user. The problem is in your form id because they're not unique. When you click on any Ban/UnBan link, JavaScript searches for the ban/unban element, finds the first one and submits that one.
The solution is very easy:
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)){
$uID = $row['id'];
if($row['banned'] == '0'){
$banBool = '<form id="ban' . $uID . '" method="post" action="ban.php?uid='.$uID.'">
<input type="hidden" name="ban" value="" />
<a onclick="document.getElementById(\'ban' . $uID . '\').submit();">Ban</a>
</form>'; }else{
$banBool = '<form id="unban' . $uID . '" method="post" action="unban.php?uid='.$uID.'">
<input type="hidden" name="unban" value="" />
<a onclick="document.getElementById(\'unban' . $uID . '\').submit();">UnBan</a>
</form>' ;
}
if($row['banned'] == '1'){
$status = 'Banned';
}else{
$status = 'Active';
}
echo "<tr><td>" . $row['username'] . " " . $uID . "</td><td>" . $banBool . "</td><td>" . $status . "</td><td>" . $row['full_name'] . "</td></tr>";
}
I just included the User ID on every form and JS call so that they are unique. (Also, your second hidden field had the name as name)
Yes, #MrFusion nailed it (+1). But I still don't see why you aren't simply doing something like this:
<?php
$query = mysql_query("SELECT id, full_name, banned, username from `tblUsers`");
while($row = mysql_fetch_array($query)) {
echo "<tr><td>{$row['username']}</td><td>{$row['id']}</td>";
if($row['banned'] == '0') {
echo "<td>Ban</td>";
}
elseif($row['banned'] == '1') {
echo "<td>Banned (Unban)</td>";
}
else {
echo "<td>Active</td>"; # Not sure what this is for in your original code
}
echo "<td>{$row['full_name']}</td></tr>";
}
?>
Then just make admin.php
<?php
include "../../includes/dataBase.class.php";
sql::connect();
if(!sql::checkAdmin() == 1){
header("Location: ../myaccount.php");
}
if(!isset($_GET['ban']) AND !isset($_GET['unban'])){
header("Location: users.php?action=1");
}
if(isset($_GET['ban'])) {
$uid = mysql_real_escape_string($_GET['ban']);
mysql_query("UPDATE tblUsers SET banned = '1' WHERE id = '{$uid}'") or die(mysql_error());
//I don't know what the following two lines are for
//but they seem to IP-ban the admin himself: you're banning the IP address
//of the user doing the ban, not the IP address of the user you are banning.
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO `uipBan` (`ip`) VALUES ('{$ip}')") or die(mysql_error());
}
elseif(isset($_GET['unban'])) {
$uid = mysql_real_escape_string($_GET['unban']);
mysql_query("UPDATE tblUsers SET banned = '0' WHERE id = '{$uid}'") or die(mysql_error());
}
header("Location: users.php?action=1");
?>
Note the importance of escaping your user input using mysql_real_escape_string, even if it's coming from a trusted user: this prevents SQL injection which could result in you losing your entire database :)