update MySQL using PHP - php

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.

Related

PHP produces blank screen with submit button click

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";

PHP Self-referencing form

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.

Why is MySQL INSERT statement not working without error

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.

Php error displaying data in input

This piece of code is working fine, what I want to is why if I remove the foreach($rows as $row) I gt an error, is there a way to display the data without using it.
<?php
require("coneccion.php");
if(empty($_SESSION['user']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
$id = $_GET['id'];
$nombre = $_SESSION['user']['username'];
$query = "SELECT c.coursename FROM courses as c WHERE c.courseid = $id and c.id = (SELECT id FROM users WHERE username = '$nombre') ";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Error");
}
$rows = $stmt->fetchAll();
?>
<?php
foreach($rows as $row):
echo '<input type="text" name="coursename" value="' .htmlentities($row['coursename']) . '" />';
endforeach;
Assuming you're working with the standard PDO settings, you can access the first returned result like so:
echo '<input type="text" name="coursename" value="' .htmlentities($rows[0]['coursename']) . '" />';
To return the first row in your array you could do:
echo '<input type="text" name="coursename" value="'
.htmlentities($rows[0]['coursename']) . '" />';
Which will return the first row, but I dont recommend this. PHP array are hashtables they are incredibly fast you don't save yourself any style points by making your code less maintainable.

Trouble with a php post back solution

This may be an easy fix, but I can't get my head around it .
Basically I've remade my blog using a database and php rather than wordpress.
I want my site to show the most recent post first, then i'm using PhP postback to alter it
So far it works, but i can't figure out a way for it to automatically go to the most recent one but then change after the postback.
<?php
$inId = $data[0];
//if (!empty($inId))
//{
//}
//else
//{
//$inId = $_POST['ID'];
//}
include 'Includes.php';
$blogPosts = GetBlogPosts($inId);
foreach ($blogPosts as $post)
{
echo "<div class='post'>";
echo "<h3>" . $post->title . "</h3>";
echo "<p2>" . $post->post . "</p2>";
echo "<span class='footer'>Posted By: " . $post->Author . " Posted On: " . $post- >datePosted . "</span>";
}
echo '<form name="myForm" action="Index.php" onsubmit="return validateFormStrings()" method="post">';
echo'<select name ="ID">';
$query4 = "SELECT * FROM Blogs ORDER BY ID ";
$result = mysql_query($query4);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<option value="'.$row['ID'].'">'.$row['Title'].'</option>';
echo '<br>';
}
echo'</select>';
echo '<input type="submit" value="Retrieve Posts">';
echo '<a href="Index.Php" ></a>';
echo '</form>';
?>
As you see i tried to fiddle with !empty and things but that's not really what im trying to do.
If i'm unclear let me know.
I almost need something like " if ( button !pressed) then its data[0] else its the postback
Thanks in advance
I found out how to do it using the isset() function.
if (isset($_POST['submit1']))
{
$inId = $_POST['ID'];
}
else
{
$inId = $data[0];
}
This checks if the submit button has doe the postback or not. Works a treat.
Gonna have a go at trying it with Ajax so I don't need the button at all ^^

Categories