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 .
Related
I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;
I'm creating this web page for this class that I'm in and for it I need to concatenate two separate HTML form inputs with a space in between and insert them into a MySQL database. Specifically I ask the user for their first name and their last name in separate HTML form inputs and I have to concatenate those two input into a full name with a space in between (or else "Bob" and "Ross" concatenated would be "BobRoss" instead of "Bob Ross"). I don't know where to start when doing that. Also I need to check that the full name isn't already in the database before inserting it into the database, but I'm already doing that with the first name and last name so that shouldn't be too hard.
Here is the HTML page with the form inputs:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>First name:</p><input type="text" name="firstname"><br>
<p>Last name:</p><input type="text" name="lastname"><br>
<p>Age:</p><input type="text" name="age"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
And here is the PHP page where it inputs the data into the database. Currently I'm inputing the user's first name, last name, and age, but I need to concatenate the first and last name and make sure it isn't in the database and then insert it into the database and I haven't done that. Currently I make sure that the first name is unique, I make sure that the last name is unique, but I don't care whether the age is unique or not.
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$name = mysql_real_escape_string($_POST['firstname']);
$query = "SELECT * FROM names_1 WHERE firstname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (firstname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['lastname']);
$query = "SELECT * FROM names_1 WHERE lastname='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "Your name is already in the database and will not be added again!";
}
else {
$query = "INSERT INTO names_1 (lastname) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your first name was successfully added to the database!";
}
else{
echo "Your first name couldn't be added to the database!";
}
}
$name = mysql_real_escape_string($_POST['age']);
$query = "INSERT INTO names_1 (age) VALUES('$name')";
$result = mysql_query($query);
if($result) {
echo "Your name was successfully added to the database!";
}
else {
echo "Your name couldn't be added to the database!";
}
mysql_close($con);
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
For a start you shouldn't be using mysql functions as this extension
is deprecated as of PHP 5.5.0, and will be removed in the future.
I suggest using the new improved PDO library and PDO Prepared Statements, see here.
As for the concatenation, you could simply do it like this:
$concatenated_name = $_POST['firstname'] . " " . $_POST['lastname'];
This would concatenate the names with a space in between.
You can then use $concatenated_name in your queries.
However I still strongly recommend you use PDO for all your functions.
$fullname = trim($_REQUEST['firstname']).trim($_REQUEST['lastname']);
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.
I'm currently working on a quiz program using PHP/mySQL (my first time ever actually using either).
Up until now I was just working on getting it all functioning correctly with the mySQL tables, and to do so I was putting all questions in a quiz on one page. However, now I want to be able to put just one question per page and then progress by submitting one answer at a time.
The way my questions are chosen to be in the quiz may be a little confusing. They all have a "quiz_id" column that corresponds to the quiz they're in. The quiz has a "length" column that specifies how many questions it will actually have. So there can be more questions with the corresponding "quiz_id" than will actually be in the quiz. The way I randomly select which questions will be included is with "$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";".
Now I'm having a lot of trouble putting just one question per page. This is because each time you progress, the next random question needs to be chosen, as long as we haven't reached the limit of $length number of questions. A counter also needs to increase that keeps track of what number question you are on, out of how many ($length). I'm not sure if I need to have two separate action scripts.. one to begin the quiz, and then one to progress between questions.
Here's my quiz.php page (start page for any quiz):
<?php
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
// define the id and length from url
$id = mysql_real_escape_string($_GET['id']);
$length = mysql_real_escape_string($_GET['length']);
// query quiz table for all columns
$query_quiz = "SELECT * FROM quizzes WHERE id = '$id' LIMIT 1";
// if quiz query fails
if(!$query_quiz_result = mysql_query($query_quiz))
{
die("Couldn't run quiz query");
}
// fetch whole array of quiz info
$quiz = mysql_fetch_array($query_quiz_result);
//query question table for all columns
$question = "SELECT * FROM questions WHERE quiz = '$id' ORDER BY rand() LIMIT $length";
$q_result = mysql_query($question) or die ("couldn't run questions query");
// store queried questions as an array to pass via session variables
$q_array = array();
while($row = mysql_fetch_assoc($q_result))
{
$q_array[] = $row;
}
session_start();
$_SESSION['quiz'] = $id;
$_SESSION['questions'] = $q_array;
$_SESSION['length'] = $length;
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<!-- create the header using the quiz id and name -->
<h1 style="text-align: center;">Quiz <?php echo $quiz['id'] ?>: <?php echo $quiz['name'] ?></h1>
<hr />
<h4>This quiz will have a total of <?php echo $length?> questions.</h4>
<button onClick="parent.location='start.php'">Begin Quiz</button>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
And here's my start.php page.. not sure if I can use this one page for all the questions, or do I need a separate action page for once the quiz has begun and you're progressing past #1?
<?php
// continue the session
session_start();
// initialize the mysql data
$connect = mysql_connect('localhost', 'root', '');
$select_db = mysql_select_db('mysql');
$quiz_id = $_SESSION['quiz'];
$length = $_SESSION['length'];
$_SESSION['questions_array'] = $_SESSION['questions'];
$current_question = array_shift($_SESSION['questions_array']);
$_SESSION['counter'] = 1;
$counter = $_SESSION['counter'];
?>
<html>
<head>
<title>Quiz <?php echo mysql_real_escape_string($_GET['id']);?></title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="container" style="margin-left: 30px;">
<h3>Question <?php echo $counter ?> of <?php echo $length ?></h3>
<hr />
<h4><?php echo $current_question['prompt']?></h4>
<?php
// define query for answers for each question
$answers = 'SELECT `prompt` FROM `answers` WHERE `quiz` = '.$quiz_id.' AND `question` = '.$current_question['id'].'';
//if failed
if(!$answers_result = mysql_query($answers)){
die("Couldn't run answers query");
}
?>
<p style="margin-left: 50px;">
<?php
// if question type is "multiple choice", loop through answer choices and print them as options
if ($current_question['if_short_answer'] == 0) {
// loop through rows of answer choices
while($a_row = mysql_fetch_array($answers_result))
{
// print each answer choice
?>
<input type='radio' name='question_<?php echo $current_question['id']; ?>' value='<?php echo $a_row['prompt']?>'><?php echo $a_row['prompt']?>
<br />
<?php
}
echo "</p>";
}
// if question type is "short answer", create text box
elseif ($current_question['if_short_answer'] == 1) {
?>
<input type="text" name="question_<?php echo $current_question['id']; ?>" /><br />
</p>
<?php
} ?>
<?php
if ($counter >= 1) { ?>
<button onClick="parent.location='next.php'">Next Question</button>
<?php
}
else { ?>
<button onClick="parent.location='start.php'">Begin Quiz</button>
<?php
}
?>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
I apologize if this is a very vague or long question.. I've just gotten myself pretty lost now and not sure how to proceed. Basically I am asking: how can I put just one question per page, progressing through random questions until a limit of $length is reached, and then a "submit quiz" button at the end leads to a score page? All along the way, the "next question" button needs to store the user's input for the current question.
I basically need guidance in writing my script to progress from one question to the next.
Thanks!
All you need to get the all questions from Database, and using jquery show()/hide() method show only one questions at a time.
I had written sample script for your requirement here.
http://www.smarttutorials.net/responsive-quiz-application-using-php-mysql-jquery-ajax-and-twitter-bootstrap/
Firstly you are re creating the $q_array on each page so it will only contain the last displayed question which will not work
try
if(isset($_SESSION['questions']))
{
$_SESSION['questions']+= ", $question_id";
}
In the select query you should omit the questions with the already displayed in the array.
I'm currently working my way through "PHP and MySQL Web Development." I've successfully created databases and been able to make tables and use the database. I've also successfully completed all the chapters on PHP and have had no problems with PHP not working up to this point. The goal of this page is return search results from a database. It's a pretty simple thing to do but for some reason nothing is being output from the script to the page. I'm getting no errors or anything. It's just blank with the title at the top. Can anyone please help me out with this? Thank you.
Here is the PHP code:
<html>
<head>
<title>Book-O-Rama Search Results</title>
</head>
<body>
<h1>Book-O-Rama Search Results</h1>
<?php
// create short variable names
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
if (!get_magic_quotes_gpc()){
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "select * from books where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo "<p>Number of books found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = $result->fetch_assoc();
echo "<p><strong>".($i+1).". Title: ";
echo htmlspecialchars(stripslashes($row['title']));
echo "</strong><br />Author: ";
echo stripslashes($row['author']);
echo "<br />ISBN: ";
echo stripslashes($row['isbn']);
echo "<br />Price: ";
echo stripslashes($row['price']);
echo "</p>";
}
$result->free();
$db->close();
?>
</body>
</html>
You're supressing the errors from the line:
# $db = new mysqli('localhost', 'bookorama', 'bookorama123', 'books');
Thats what the # sign does, remove the # sign and verify that the connection works properly, it might be that your script fails there.
You shouldn't use that, it's not considered good practice as far as I know.
It worked for me! no white page! If you work with a editor including ftp sometimes saving the file failes. than you get a blank file. in that case safe your code and reopen the file.
as for the sql injection try this:
$searchtypes = array('type1','type2');
if (!in_array($searchtype,$searchtypes) || $searchterm=='') {
echo 'You have not entered search details. Please go back and try again.';
exit;
}
You need to create another php page that sends a post request. Here is a sample one:
Take a look at the fiddle:
<html>
<head>
<title>Book-O-Rama Search </title>
</head>
<body>
<h1>Book-O-Rama Search</h1>
<form id='uploadform' method='post' enctype='multipart/form-data' action='link to your search action php page'>
<legend>Submit form</legend><br/>
<div class='form-inputs'>
SearchType <input name='searchtype' id='searchtype'/><br>
SearchTerm <input name='searchterm' id='searchterm'/><br>
<input type="submit" value= "Search" />
</div>
</form>
</body>
</html>