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";
Related
I'm a beginner in PHP and what I need to do is delete from my uploads folder as well as deleting a row of information in the database from phpMyAdmin. I know I have to implement an unlink, but I'm not sure how to place it in my code. Any help would be appreciated. Thank you.
$dbc = mysqli_connect('localhost', 'root', 'root', 'myimages');
$files = glob("uploads/*.*");
if (isset($_GET['id']) && is_numeric($_GET['id']) ) {
$query = "SELECT title FROM imagedata WHERE id={$_GET['id']}";
if ($r = mysqli_query($dbc, $query)) {
$row = mysqli_fetch_array($r);
print '<form action="delete_image.php" method="post">
<p style="color: red;">Are you sure you want to delete this image?</p>
<p><h4>' . $row['title'] . '</h4><br>
<input type="hidden" name="id" value="' . $_GET['id'] . '">
<input type="submit" name="submit" value="Delete this image"></p>
</form>';
} else {
print '<p style="color: red;">Could not retrieve the image because:<br>' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} elseif (isset($_POST['id']) && is_numeric($_POST['id'])) {
$query = "DELETE FROM imagedata WHERE id={$_POST['id']} LIMIT 1";
$r = mysqli_query($dbc, $query);
if (mysqli_affected_rows($dbc) == 1) {
print '<p>The image has been deleted.</p>';
} else {
print '<p style="color: red;">Could not delete the image because:<br>' . mysqli_error($dbc) . '.</p><p>The query being run was: ' . $query . '</p>';
}
} else {
print '<p style="color: red;">This page has been accessed in error.</p>';
}
mysqli_close($dbc);
What column name do you use to store the file path? You will need to retrieve this as part of your first query:
$query = "SELECT title FROM imagedata WHERE id={$_GET['id']}";
Becomes:
$query = "SELECT title,path FROM imagedata WHERE id={$_GET['id']}";
And then you can use unlink() just above the database query:
unlink( $row['path'] ); // if you store full path + filename
unlink( '/path/to/your/uploads/folder/here/' . $row['path'] ); // if you store just the file name and not folder
$query = "DELETE FROM imagedata WHERE id={$_POST['id']} LIMIT 1";
$r = mysqli_query($dbc, $query);
If yo have the name of the file you could try something like
unlink($file);
This after you have removed it from your db
Then print the has been removed message
I have the facility to update what I call 'documents' (ver similar to creating a post) on my cms which works fine but I have introduced categories where the documents are associated to them. Now I have managed to bind them when creating the doc from new but when trying update them I am getting a bit stuck. I am using checkboxes to show the list of categories and when selected it updates a join table which uses the doc_id and the cat_id.
Here is the script for updating the doc:
<?php
include ('includes/header.php');
require ('../../db_con.php');
echo '<h1>Document Edit</h1>';
// Check for a valid document ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_docs.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
exit();
}
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
// Check for a document name:
if (empty($_POST['doc_name'])) {
$errors[] = 'You forgot to enter your document name.';
} else {
$dn = mysqli_real_escape_string($dbc, trim($_POST['doc_name']));
}
// Check for a document content:
if (empty($_POST['doc_content'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$dc = mysqli_real_escape_string($dbc, trim($_POST['doc_content']));
}
if (empty($errors)) { // If everything's OK.
// Test for unique doc title:
$q = "SELECT doc_id FROM docs WHERE doc_name='$dn' AND doc_id != $id";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) == 0) {
// Make the query:
$q = "UPDATE docs SET doc_name='$dn', doc_content='$dc', doc_name='$dn' WHERE doc_id=$id LIMIT 1";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
$doc_id = mysqli_insert_id($dbc);
$query = "UPDATE doc_cat_join (cat_id,doc_id) VALUES ";
$cat_ids = $_POST['cat_id'];
$length = count($cat_ids);
for ($i = 0; $i < count($cat_ids); $i++) {
$query.='(' . $cat_ids[$i] . ',' . $doc_id . ')';
if ($i < $length - 1)
$query.=',';
}
// Print a message:
echo '<p>The document has been edited.</p>';
} else { // If it did not run OK.
echo '<p class="error">The document could not be edited due to a system error. We apologize for any inconvenience.</p>'; // Public message.
echo '<p>' . mysqli_error($dbc) . '<br />Query: ' . $q . '</p>'; // Debugging message.
}
} else { // Already used.
echo '<p class="error">The document name has already been used.</p>';
}
} else { // Report the errors.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo " - $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
} // End of if (empty($errors)) IF.
} // End of submit conditional.
// Always show the form...
// Retrieve the document's information:
$q = "SELECT * FROM docs WHERE doc_id=$id";
$r = mysqli_query ($dbc, $q);
if (mysqli_num_rows($r) == 1) { // Valid document ID, show the form.
// Get the document's information:
$row = mysqli_fetch_array ($r, MYSQLI_NUM);
// Create the form:
echo '<form action="edit_doc.php" method="post">
<p>Document Name: <input type="text" name="doc_name" size="15" maxlength="15" value="' . $row[1] . '" /></p>
<textarea name="doc_content" id="doc_content" placeholder="Document Content" style="display: none;"></textarea>
<iframe name="editor" id="editor" ></iframe>'
?>
<div class="row">
<div class="col-group-1">
<?php
$q = "SELECT * FROM cats";
$r = mysqli_query ($dbc, $q); // Run the query.
echo '<div class="view_body">';
// FETCH AND PRINT ALL THE RECORDS
while ($row = mysqli_fetch_array($r)) {
echo '<br><label><input type="checkbox" name="cat_id[]" value="' . $row['cat_id'] . '">' . $row["cat_name"] . '</label>';
}
echo '</div>';
?>
</div>
</div>
<br><br>
<input onclick="formsubmit()" type="submit" value="Update Document" name="submit"/>
<?php echo'
<input type="hidden" name="id" value="' . $id . '" />
</form>
<br><br>Back to docs list';
} else { // Not a valid document ID.
echo '<p class="error">This page has been accessed in error.</p>';
}
?>
<?php
mysqli_close($dbc);
?>
So I have three tables:
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
doc_id
cat_id
the join table related the doc_id and cat_id which then associates them together. I am guessing in my script when I update a doc it will need to delete the rows and then re-insert them? I just need to know a way or the easiest way of updating the join table as I am a tad stuck...
In case of checkbox update you need to delete previous stored checkbox of with appropriate id and insert new one you can't update checkbox as we can't predict how many checkbox will be selected by user....
Case:
It may happen that user remove one checkbox at update time so you will never know which one to be deleted.......
In your code...
docs
doc_id
doc_name
doc_content
cats
cat_id
cat_name
doc_cat_join
id
doc_id
cat_id
here you have to delete old checkbox of updation doc,
DELETE FROM doc_cat_join WHERE cat_id = some_id
next you can insert selected checkbox as you are inserting first time...
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']."',
I'm trying to create a PHP forum page uses sessions. Every time I try to post a comment I keep getting the same error, not sure where I'm going wrong with this
Here's my code for the form:
session_start();
if(!isset($_SESSION['user_id'])){
require('login_tools.php');
load();
}
$page_title = 'Post Message';
include('includes/header.html');
echo "<h1>Home</h1>
<p>You are now logged in, {$_SESSION['first_name']}
{$_SESSION['last_name']}
</p>";
echo '<form action = "post_action.php" method = "POST" accept-charset = "utf-8">
<p>Subject:<br/>
<input name = "subject" type = "text" size = "64"</p>`
<p>Message:<br/>
<textarea name = "message" rows = "5" cols = "50">
</textarea></p>
<p><input type = "submit" value = "Submit"></p>
</form>';
Here's the code for the post action:
session_start();
require('login_tools.php');
if(!isset($_SESSION['user_id'])){
load();
}
$page_title = 'Post Error';
include('includes/header.html');
echo '<div id = "content">';
if($_SERVER['REQUEST_METHOD']=='POST'){
if(empty($_POST["subject"])){
echo '<p class = "main">Please enter a subject for this post</p>';
}
if(empty($_POST["message"])){
echo '<p class = "main">Please enter a message for this
post';
}
if(!empty($_POST['subject']) && !empty($_POST['message'])){
require('../connect_db.php');
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
VALUES(
'{$_SESSION[first_name]}',
'{$_SESSION[last_name]}',
'{$_POST[subject]}',
'{$_POST[message]}',
NOW())";
$r = mysqli_query($dbc,$q);
if(mysqli_affected_rows($dbc)!=1){
echo '<p>Error</p>'.mysqli_error($dbc);
}
else{
load('forum.php');
}
mysqli_close($dbc);
}
}
There is a spelling mistake
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
It should be message
The PHP statement which generates the SQL is missing quote marks around the member names of $_SESSION.
I would write
$q = "INSERT INTO forum
(first_name,last_name,subject,messsage,post_date)
VALUES('" .
$_SESSION['first_name'] . "','" .
$_SESSION['last_name'] . "','" .
$_POST['subject'] . "','" .
$_POST['message'] . "'," .
"NOW())";
(PROBLEM IS VERY DETAILED FOR TOO LONG DIDN'T READ: "My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.")
Hello! The following codes purpose is to do a basic search in the database. The data is passed by a form. The tutorial I was using was written by: 'Frost of Slunked.com' and it was a basic register/login php MySQL tutorial, which worked perfectly. I managed to write a woking table-updater function and form-submit to add new data to the selected (so that's working as intended.
config.php - conncets to the MySQL server, selects the database, starts the session, requires the functions.php (with authors comments included)
<?php
/*****************************
File: includes/config.php
Written by: Frost of Slunked.com
Tutorial: User Registration and Login System
******************************/
// start the session before any output.
session_start();
// Set the folder for our includes
$sFolder = '';
/***************
Database Connection
You will need to change the user (user)
and password (password) to what your database information uses.
Same with the database name if you used something else.
****************/
mysql_connect('localhost', 'myusername', 'mypassword') or trigger_error("Unable to connect to the database: " . mysql_error());
mysql_select_db('tormex') or trigger_error("Unable to switch to the database: " . mysql_error());
/***************
password salts are used to ensure a secure password
hash and make your passwords much harder to be broken into
Change these to be whatever you want, just try and limit them to
10-20 characters each to avoid collisions.
****************/
define('SALT1', '24859f##$##$');
define('SALT2', '^&##_-=+Afda$#%');
// require the function file
require_once 'functions.php';
// default the error variable to empty.
$_SESSION['error'] = "";
// declare $sOutput so we do not have to do this on each page.
$sOutput="";
?>
functions.php - has multiple functions (login, createRide, Register etc.). Most of the functions purpose is to get the values from the submitted HTML forms and then maintain the required actions - I will only mentioned my searchRide function (which in my guess has the error or atleast, has to do something with it) and the createRide function, which is working properly.
<?php ...
unction searchRide($pWhen_min, $pWhen_max, $pFrom, $pTo){
if (!empty($pWhen_min) && !empty($pWhen_max) && !empty($pFrom) && !empty($pTo)) {
global $sql2, $query2;
$sql2 = "SELECT * FROM ride WHERE `from` ='$pFrom' AND `to` = '$pTo' AND `when` >= '$pWhen_min' AND `when` <= '$pWhen_max' ";
$query2 = mysql_query($sql2) or trigger_error("Query Failed: " . mysql_error());
}
}
function createRide($pFrom, $pTo, $pWhen, $pSeats, $pPrice, $pCar){
if (!empty($pFrom) && !empty($pTo) && !empty($pWhen) && !empty($pSeats) && !empty($pPrice) && !empty($pCar)){
$sql = "SELECT id FROM users WHERE username= '" . $username . "' LIMIT 1";
$result = mysql_query($sql);
if(!$result) {
trigger_error("ELKURTAD " . mysql_error());
}
$row = mysql_fetch_array($result);
$sql = "INSERT INTO ride (`from`, `to`, `when`, `seats`, `price`, `car`, `u_id`)
VALUES ('" . $pFrom . "', '" . $pTo . "', '" . $pWhen . "',
'" . $pSeats . "', '" . $pPrice . "', '" . $pCar . "', '" . $result . "');";
$query = mysql_query($sql) or trigger_error("Query Failed: " . mysql_error());
if ($query) {
return TRUE;
}
}
return FALSE;
}
...?>
searchRide.php - checks if the variables which are dedicated to get the search filter values have any values; (in the else statement) if there are no values, the form wasn't submitted and displays the searchRide form and after result passes the variables for the searchRide.php ( $_SERVER['PHP_SELF'] )
<?php
require_once 'config.php';
$sOutput .= '<div id="searchRide-body">';
if (isset($_GET['action'])) {
switch (strtolower($_GET['action'])) {
case 'searchride':
if (isset($_POST['when_min']) && isset($_POST['when_max']) && isset($_POST['from']) && isset($_POST['to'])) {
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
while($row = mysql_fetch_array($query2)){
$sOutput .= "' ID: '" .$row['id'] . "' <br />
When: '" . $row['when'] . "' <br />
From: '" . $row['from'] . "' <br />
To: '" . $row['to'] . "' <br />
Seats left: '" . $row['seats'];
}
}
}
}
}else{
if (isset($_SESSION['error'])) {
$sError = '<span id="error">' . $_SESSION['error'] . '</span><br />';
}
$sOutput .= '<h2>Search for rides</h2>
' . $sError . '
<form name="searchride" method="post" action="' . $_SERVER['PHP_SELF'] . '?action=searchride">
From: <input type="text" name="from" value=* /><br />
To: <input type="text" name="to" value=* />
When_min: <input type="text" name="when_min" value=* />
When_max: <input type="text" name="when_max" value=* />
<br /><br />
<input type="submit" name="submit" value="Search" />
</form>
<br />
<h4>Would you like to Go back?</h4>';
}
echo $sOutput . "<br />";
echo "TEST string" . "<br />";
echo $query2 . " query2<br /> ";
echo $sql2 . " sql2<br />";
echo $row . "<br />";
?>
At the end of this code You can see some printed variables, which are used to check their values after searRide form is submitted.
I updated my database with the following data and checked with phpMyAdmin for the exact values so I can test the search with existing data:
From: TEST01
To: TEST02
When: 500
Seats: 5
Price: 7
Car: volvo
Test data submitted with the searchRide form:
From: TEST01
To: Test02
When_min: 1
Whn_max: 3000
After is press Search button on the searchRide form these are the following results (what the browser shows):
(sOutput variable
TEST WRITE TEXT
Resource id #5 (query2 variable
SELECT * FROM ride WHERE from ='TEST01' AND to = 'TEST02' AND when >= '1' AND when <= '5000' (sql2 variable
(row variable
After this I inserted the SQL query in the phpMyAdmin SQL command line and resulted the data I was searching for.
Was trying many times to figure out what could be the problem, with my own knowledge and varius searches on google, php.net and w3chools.com.
My guess is that i'm using the MYSQL_FETCH_ARRAY wrong.
following condition will not work
if (searchRide($_POST['when_min'], $_POST['when_max'], $_POST['from'], $_POST['to'])) {
as you have not return any value from searchRide function you need to return true to go into the condition.