I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.
Related
I have retrieve data from lvl2itquepaper and display it with textarea and save the user input to another table call lvl2itresult but when I press save, it save the last user input only.
For example, got 2 question with 2 text area, 1st text area are 'A' and 2nd text area are 'B', it save both user input as 'B'
<?php
include('../dbconnect.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Online Examination System</title>
</head>
<body>
<div id="container">
<h1>Level 2 IT Question Paper</h1>
<h2>Please read the question carefully and answer it confidently. Good Luck All!</h2>
<?php
if(isset($_POST['Submit']))
{
$sql="SELECT * from lvl1itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
$student_ans = $_POST['studentans'];
$sql="insert into lvl2itresult (questionno, question, studentans, username) values ('.$questionno.', '$question', '$student_ans', '".$_SESSION['login_user']."')";
$submit = $mysqli->query($sql);
}
}
?>
<form method= "post">
<?php
echo "Welcome, ";
$sql="SELECT * from lvl2itstudent WHERE username= '".$_SESSION['login_user']."'";
$find_student = mysqli_query($mysqli, $sql);
$check_student = mysqli_num_rows($find_student);
if ($check_student>0){
while($row = $find_student->fetch_assoc())
{
echo $row['username'];
}
}
echo "<br><br><br><br>";
$sql="SELECT * from lvl2itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
if($check_que>0){
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
echo "".$questionno. "." .$question."<br>";
echo "<textarea name='studentans' rows='5' cols='50'></textarea><br><br>";
}
}
else {
echo "there is no data in database";
}
?>
<input type="submit" value = "Submit" name= "Submit" style= "width:60px; height:30px";>
</form>
</div>
</body>
This is pretty easy, but hard to explain in a few words. What's pretty much going on is that only one parameter is being sent in the POST data since no array has been set; furthermore PHP is not treating the information as arrays either, so there's only one value to be interpreted. In any case, if the data was sent correctly, PHP would identify the POST value as an array of 2 dimensions, outputting a SQL error for not being able to parse the data as a string.
To solve this, first change your <textarea> tag as follows:
<textarea name='studentans[]' rows='5' cols='50'></textarea>
The brackets will tell HTML that there will be many elements with the name studentans.
Now breaking into your insert logic, you need to treat the arrays getting the values using indexes. Usually these will start on 0, so we will work with that:
$i = 0; // $i stands for index.
while ($row=$run_que->fetch_assoc()){
$questionno = $row['questionno'];
$question = $row['question'];
$student_ans = $_POST['studentans'][$i]; // this is where the magic happens
$sql="insert into lvl2itresult (questionno, question, studentans, username) values ('$questionno', '$question', '$student_ans', '".$_SESSION['login_user']."')";
// please also notice I deleted 2 concatenating dots near "values ('$questionno',"
$submit = $mysqli->query($sql);
$i++; // increment by 1 so we can access the next value on the next loop
}
And that should do it. I hope I didn't forget any detail.
I'm a student using NetBeans to create very basic webpage(s) using HTML, PHP and SQLite. So far, everything is fine. The problem I have is that images aren't displayed on the moviedetails.php page. Everything else including the titles, ratings and description for each table entry works fine. (I am retrieving rows from a database table.) Here is my code:
(This is very new to me, so if it's a simple mistake, sorry for wasting your time :/)
Index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Import SQLite database "movies.db" to a Var
$query = $pdo->query("SELECT * FROM movie");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//For each id number in db, echo a hyperlink containing that ID's title and
echo '' . htmlentities($row['title']) . '';
echo '<br>';
}
?>
</body>
moviedetails.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$pdo = new PDO('sqlite:movies.db'); //Using movies.db
$query = $pdo->prepare("SELECT * FROM movie WHERE id=:id"); //Prepare this statement
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT); //GET INPUT from Variable 'id' and FILTER anything which isn't a number
$query->bindParam(':id', $id, PDO::PARAM_INT); //Bind :name 'id' to a $id variable
$query->execute(); //Execute the prepared statement
$row = $query->fetch(PDO::FETCH_ASSOC); //Fetch next row of results
//var_dump($row);
//display title, description and rating
echo '<h1>'.htmlentities($row['title']).'</h1>'; //Echo 'Title' from db into a heading
echo ''; //Echo 'image from db into a link
echo '<p>'.htmlentities($row['description']).'</p>'; //Echo 'description' from db to paragraph
echo '<p>Rating: '. htmlentities($row['rating']).'</p>'; //Echo 'rating' from db to paragraph
?>
</body>
Here is my database in an image, as this is the easiest way to show you:
http://i.cubeupload.com/TBI5Fv.png
Here is one of the webpages that should diplay a link. However, it contains only the other table fields:
http://i.cubeupload.com/1tcfsU.png
The strange thing is, it doesn't give me any errors, so I don't know where I'm going wrong.
Hope someone can help :)
Your <a> tag is empty, so it's invisible.
echo '';
You should put some content that will be displayed as a link like this:
echo 'THIS IS LINK TO IMAGE';
If you want to display the image itself instead of a link, you should use <img> tag like this:
echo '<img src="'.htmlentities($row['image']).'"/>';
Requesting some help on this task management system that i am making for class. I cant quite get it to work right. information is sometimes lost before it gets to the server and some of the last php code leeks thru to being seen on the site. can anyone tell me what i am doing wrong and help me to fix this? this code is supposed to allow you to send the task to a data base and the managing section relays the data from the database to the webpage.
data base is set up as this
3 Columns:
id - INT - 5 Length - Primary Key - AI.
description - VARCHAR - 255 Length.
active - BOOLEAN - 1 Length.
I am creating this on the hostica text editor that is within the site not an IDE if there are any discrepancy in the code
the website link is http://jtaylor84.net/taskmanager.php
I would like this code to work to take the information entered and relay it to the database and show in the managed tasks in order to have them up to be removed and show the tasks that have been entered.
<!DOCTYPE html>
<html>
<head>
<title>Online Task Manager</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div id="main">
<?php
$con = mysqli_connect('localhost', 'root', '', 'Jhonny3_Task_Manager') or die(mysql_error());
if (isSet($_POST['createTask'])) {
if (isSet($_POST['desc']) && $_POST['desc'] != '') {
$desc = $_POST['desc'];
$q = mysqli_query($con, "INSERT INTO `tasks` VALUES ('', '$desc', '1')") or die(mysql_error());
if ($q) { echo 'Added task.';
}else
echo 'Failed to add task.';}}
if (isSet($_GET['removeTask']) && isSet($_GET['id'])) {
$id = $_GET['id'];
$q = mysqli_query($con, "UPDATE `tasks` SET `active`='0' WHERE `id`='$id'");
if ($q) { echo 'Task removed.';
}else
echo 'Failed to remove task.';}
?>
<h1>Add Task:</h1>
<form action='taskmanager.php' method='POST'>
Description of Task: <input type='text' name='desc'/>
<input type='submit' value='Create Task' name='createTask'/>
</form>
<h1>Manage Tasks:</h1>
<?php
$qu = mysqli_query($con, "SELECT * FROM `tasks` WHERE `active`='1'");
if (mysqli_num_rows($qu) > 0) {
after this section the code shows up on the web page and i am not sure why
while ($row = mysqli_fetch_array($qu)) {
echo "";
echo $row['description'];
echo "<a href='taskmanager.php?removeTask&id=".$row['id']."'>Remove Task</a>";
}
}
?>
<footer id="foot01"></footer>
</div>
<script src="sitescript.js"></script>
</body>
</html> `
Problem might be your php server .your code working fine in my server .
He guys,
For school I need to make a website where you can play flash games,
rate games by leaving reactions in a text form and a vote system which uses a number system (i.e. 1 = extremely bad and 10 = very good.).
Right now what I want to do is this:
Have an index page for each category of games where users can click on a games name and be directed to another page where the script loads the game.
So far I've written this code for the index (master) page.
<!DOCTYPE html>
<?php
include("dbconnect.php");
?>
<html>
<head>
<meta charset="UTF-8">
<title>Master page</title>
</head>
<body>
<?php
//Place all data from this mySQL query in $result.
$result = mysql_query("SELECT * FROM gamesDB");
//While a row of data exists, put that row in $data as an associative array.
while($data = mysql_fetch_assoc($result)) {
//Echo a link to all the games in the MySQL database.
echo "<a href='detail.php?id=" . $data['ID'] . "'>";
//Echo the games name in the url.
echo $data['Spel'];
//Echo the closing tags
echo "</a>";
echo "<br />";
}
?>
</body>
</html>
And this is for the game (detail) page.
<!DOCTYPE html>
<?php
include("dbconnect.php");
?>
<html>
<head>
<meta charset="UTF-8">
<title>Detail page</title>
</head>
<body>
<?php
//Place all data out of the database, with the ID number retrieved out of the url into $result.
$result = mysql_query("SELECT * FROM gamesDB WHERE id = '" . $_GET['id'] . "'");
//While a row of data exists, put that row in $data as an associative array.
while($data = mysql_fetch_assoc($result)) {
//Retrieve the files name from the database and place it in the <embed> tags as src="...".
echo "<embed width='800' height='512' src='" . $data['file'] . "' type='application/x-shockwave-flash'></embed>";
//Echo the games name
echo "Spel: " . $data['Spel'] . "<br />";
//Echo the points (not yet functional)
echo "Punten: " . $data['Punten'] . "<br />";
//Echo all reactions from users regarding this game.
echo "Reacties: " . $data['Reactie'] . "<br />";
}
?>
</body>
</html>
When I click on the link in the masterpage I get redirected to the detail page but unfortunately, the game does not load.
In my MySQL DB I added the file name to the first row with ID 1. I thought, when I inquire for the filename in the tags it would load the game but it says (when I right click the box in which the game should display) "Movie not loaded...".
Can anybody help me get this to work ? Is my thinking way off perhaps, or am I headed in the right direction.
Since it is an assignment for school, there is no need to worry about any SQL injection vulnerabilities.
Thanks!
I actually forgot to put an entry into the file column.
Now that the problem I had with "<embed>" has been resolved, I would like to focus on how to add user comments to my 'comments' column, and have each comment displayed. I'd like to find the code myself as much as possible so you could just react to my question with pointers instead of writing the complete code I would be very grateful.
I'm trying to get a row from the DB using php, i've made an html form that's supposed to take a book title from users and gets the review from the DB about this book, and then post it in an input text, the form's action leads to the following function :
function GetReview($BookTitle)
{
require'DB.php';
if(empty($_POST['BookTitle']))
{
echo " You must enter a book name!";
return false;
}
$BookTitle = mysql_real_escape_string($BookTitle);
$q="Select Reviews from Users_Booklist where (Book_Title like '%" .$BookTitle."%');";
if(!mysql_query($q,$con))
{
die("Error".mysql_error());
}
else
{
$row = mysql_fetch_row($q);
?>
<html>
<head><title>Delete Review </title>
</head>
<body>
<br>
<form name="DeleteReview " action="DeleteReviewsFunction.php" method="post">
Review: <input type="text" name="Review" size="200" value="<?php echo $row[0]; ?>"/>
<input type="submit" value="Delete Review" />
</form>
</body>
</html>
<?php
}
}
GetReview($_POST['BookTitle'])
However, it leads me to the next form with nothing in the input text and this warning:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\GetReview.php on line 20
I've searched and tried different code but still same result.
Could anyone please tell me where the error is???... Thanks
$qq = mysql_query($q,$con);
if(!$qq) {
// (...)
$row = mysql_fetch_row($qq);
I'm not going to be a lot of help, but your question seems to be where the error is occuring, and I can tell you that.
It's in the $row = mysql_fetch_row($q); line.
You can tell this because the error record starts with mysql_fetch_row(), and the above line is the only mention of mysql_fetch_row() in the code.
Check the SQL query by printing the output of $q variable with:
echo $q;
Now, try to execute it from your MySQL client. Collect the results (if there are) and check for errors.
A suggestion: If you want, you can use a tool like ezSQL that can be very useful (especially for code organization)