0

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.

My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.

HTML CODE:

<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text"  placeholder="Question Title" ></textarea> </p>
<textarea name="detail"  id= "detail_layout" type="text" placeholder="Question Details"  ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" /> 
</form>

PROCESS.PHP CODE:

$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];

$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";

$result = mysql_query("SELECT * FROM questions where detail='$detail' ") 
or die(mysql_error());  

The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!

Updated Version

QUESTION_EXAMPLE.PHP CODE

<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);

mysql_select_db($database) or die( "Unable to select database");

$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);

$row = mysql_fetch_assoc($result);

mysql_close($conn);

?>

<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Asciiom
  • 9,867
  • 7
  • 38
  • 57
user1691618
  • 15
  • 2
  • 6
  • Change the query to have "where id=$id" and instead of passing the detail (or, I assume text part) of the question, have the ID passed and then retrieved by your "get" – gloomy.penguin Sep 23 '12 at 00:11
  • Yes, I've tried doing "where question_id='$question_id'" but I don't know how to define the question_id in the html page so that when I do a $_get it actually retrieves it – user1691618 Sep 23 '12 at 00:17
  • stick `if(!$result) die(mysql_error());` before the line `$row = mysql_fetch_assoc($result);`, what does it say? – Stuart Wakefield Sep 23 '12 at 02:27
  • When I add that line, I get the error _Unknown column 'id' in 'where clause'_ and then if I change the `WHERE id = "` to `WHERE id = ''"` I get the error _You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '72' at line 1_ (72 was id number) – user1691618 Sep 23 '12 at 02:33
  • Is the database column named something different? Looking up you it seems it might be `question_id` try changing `WHERE id =` to `WHERE question_id =` – Stuart Wakefield Sep 23 '12 at 02:38
  • It works! Thank you soooo much!!! I have honestly been trying to figure this out all day. You have been such a big help, even more than my tutor, who had a tough time understanding what I was trying to say, and kinda kept avoiding the issue haha. Now I can replicate this process in other parts of my website. – user1691618 Sep 23 '12 at 02:47
  • Sweet! Glad I could help you out – Stuart Wakefield Sep 23 '12 at 02:51
  • I would love it if I could continue to work with you on some of my problems. I currently have a tutor whose eh alright, and he gets the job done, but when problems like this arise, I would love to be able to email someone like you, who spends this much time helping a person he doesn't even know, and for free. If you're interested, let me know, and we can work out the logistics like price per email/solution etc... – user1691618 Sep 23 '12 at 02:52

3 Answers3

2

Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.

How can I prevent SQL injection in PHP?

So you have a form...

[title]

[details]

[submit]

And that gets inserted into your database...

INSERT INTO questions (title, details) VALUES (?, ?)

You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.

$id = mysql_insert_id();

Then you can get the record...

SELECT title, details FROM questions WHERE id = ?

And output it in a preview page.

I have written an example using PDO instead of the basic mysql functions.

form.php:

<form action="process.php" method="post">
    <label for="question_title">Title</label>
    <input id="question_title" name="title"/>
    <label for="question_detail">Detail</label>
    <input id="question_detail" name="detail"/>
    <button type="submit">Submit</button>
</form>

process.php:

<?php

// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();

// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);

?>

<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>

Without PDO...

form.php:

<form action="process.php" method="post">
    <label for="question_title">Title</label>
    <input id="question_title" name="title"/>
    <label for="question_detail">Detail</label>
    <input id="question_detail" name="detail"/>
    <button type="submit">Submit</button>
</form>

process.php:

<?php

// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" . 
    mysql_real_escape_string($_POST["title"]) . "','" .
    mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);

header("Location: question_preview.php?id=$id");

question_preview.php:

<?php

// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
    mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);

?>

<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Community
  • 1
  • 1
Stuart Wakefield
  • 6,294
  • 24
  • 35
  • First off, what do ou mean when you say escaping the sql parameters. I'm still new with all of this, and I'm still catching up with all the terminology. Second, are the question marks just placeholders in your example, because I have $title, and $details for the values. If they are placeholders, what is the ? referring to with the id= statement... – user1691618 Sep 23 '12 at 00:32
  • Okay, I really do appreciate you going to this much effort to explain this to me, but why would this way be better than just generating a random unique number on the html page, and then retrieving that number on the php page, as other members have suggested? – user1691618 Sep 23 '12 at 00:50
  • No problems, because when you write a database statement such as `SELECT * FROM questions WHERE detail = $detail` and you are getting `$detail` from the url, someone can add in some very nasty stuff. Imagine they went to process.php?detail=';DROP DATABASE; They could tell the database to do all sorts, by escaping the value you stop them from doing that. I've added an example using PDO to illustrate the difference. – Stuart Wakefield Sep 23 '12 at 00:50
  • The suggestion of using PDO is additional to the solution, I would recommend it as your code will be safer. Really you do not need to create a new identifier as you already have one in the form of your `id` column in the database. The function `mysql_insert_id()` retrieves the auto increment id of the last inserted record in the database. – Stuart Wakefield Sep 23 '12 at 00:54
  • Okay, right now I'm looking for functionality, as I am still a ways from getting the site up and running. I definitely appreciate the safety tips, and I will definitely spend time making sure my site is safe and secure before it goes up. I'll try the insert statement now to see if I can get that to work, and I'll let you know if I found it successful or not.... THANK YOU! – user1691618 Sep 23 '12 at 00:59
  • Okay so I tried using your method, but couldn't get it to work... Here's the code I used `$query= "INSERT INTO questions (title, detail) $question_id = mysql_insert_question_id(); VALUES ('$title', '$detail)";` and then `$result = mysql_query("SELECT * FROM questions where question_id='$question_id' ")` – user1691618 Sep 23 '12 at 01:06
  • I've updated my answer to give a full example using the mysql functions in PHP... Hopefully it is more useful to you – Stuart Wakefield Sep 23 '12 at 01:13
  • Okay, I went through you're updates, and did everything almost exactly as you did (with the addition of my database info) but got an error on the process.php page saying _Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /www/zxq.net/w/h/a/whatisit/htdocs/question_preview.php on line 21_ I feel like I'm really close, and it makes sense logically. I'll keep trying, hopefully you know what's causing the error... – user1691618 Sep 23 '12 at 01:37
  • Okay now I'm completely lost haha. I swear there used to be 3 separate pages, not just form.php and process.php. That's the model I was following, will an in-between page that re-directed users to the page where there questions were shows=n. Did you re-re-update, or have I been looking at a computer screen too long today haha – user1691618 Sep 23 '12 at 01:49
  • Oh sorry I didn't realise you'd moved over to the three page model, I changed it to two page to hopefully make it clearer. I'll put it back. Make sure you are capturing the `$result` from `mysql_query(...)` and plugging that into `mysql_fetch_assoc($result)` – Stuart Wakefield Sep 23 '12 at 02:00
  • yah I tried doing the 2 page model and kept getting errors with the $conn, but didn't seem to be having that problem with the 3 pg model. I'll try it again, and if it would be easier, I can make a new post and show all of my code for the 3 pages... – user1691618 Sep 23 '12 at 02:03
  • Okay so I feel like I'm so close, and you're answer makes complete sense logically, but I'm still getting held up on that same error message. The question_id seems to be working, as the correct id is in the url, but the page only loads with an error message. I will make an answer to this question with the code I am using just so you can see what I did... – user1691618 Sep 23 '12 at 02:18
0

I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command

example -

$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
Ashish Agarwal
  • 14,555
  • 31
  • 86
  • 125
  • The sorting method would be for the page that has all the questions, but what I was looking for was essentially the preview page, where it shows the user his question preview before he submits it. I want it to show him his question according to the $question_id, not $details – user1691618 Sep 23 '12 at 00:12
0

For these type of examples, you need to run Transaction within database below are the

http://dev.mysql.com/doc/refman/5.0/en/commit.html

Or else

Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.

id | question_code | q_title

question_code is the random value generated before insertion into database,

and save the question_code in a session and again call it for preview.

Rafee
  • 3,975
  • 8
  • 58
  • 88
  • If I was to create a random question_code to replace the primary key id, how would I go about doing that, and would you recommend using that beyond the preview page. Also, is there a way to set the random question_code to never repeat, because if there was the chance of it repeating, it would kind of defeat the purpose... – user1691618 Sep 23 '12 at 00:26
  • make `question_id` as `primary key`, and `question_code` as `unique_key` and there is random number generation similar to that of `Microsoft GUID` stuff.. here it is http://php.net/manual/en/function.uniqid.php – Rafee Sep 23 '12 at 00:34
  • Okay so I understand what you're suggesting, but not really how I would go about doing it. Would the random number generator go on the html page or the process.php page. The way I want to try to do it is have a random number generated on the html page, and have it hidden, and then have a _GET statement on the process.php retrieving that random number. – user1691618 Sep 23 '12 at 00:45
  • Yes!, you are generating a random number and also storing in a variable, then you do whatever you want, whether you transfer the variable using `POST` or `GET`... – Rafee Sep 23 '12 at 00:50
  • The example in the link you posted seems to have the random number generator on the php page, not the html page... – user1691618 Sep 23 '12 at 01:08
  • I didnt got that php and html page, can you define those. – Rafee Sep 23 '12 at 01:11