YH I used that look a tthe new_threads.php i put the session start start after the first php tag.
| SitePoint Sponsor |
YH I used that look a tthe new_threads.php i put the session start start after the first php tag.
yep i did put the session_start at teh top of new_threads.php but the errors im getting is:
Undefined variable: userID in C:\wamp\www\Forum\index.php on line 13
( ! ) Notice: Undefined variable: userId in C:\wamp\www\Forum\threads.php on line 8 Call Stack #TimeMemoryFunctionLocation 10.0006677488{main}( )..\index.php:0 20.0042705016include( 'C:\wamp\www\Forum\threads.php' )..\index.php:22 " method="post">
( ! ) Notice: Undefined variable: userId in C:\wamp\www\Forum\threads.php on line 9 Call Stack #TimeMemoryFunctionLocation 10.0006677488{main}( )..\index.php:0 20.0042705016include( 'C:\wamp\www\Forum\threads.php' )..\index.php:22 ">


Sorry, my comment on my code wasn't clear:
Replace $userID with $_POST['username'] as you do not have a variable named $userID.PHP Code:$_SESSION['userID'] = $userID;
Then in threads.php remove all references to $userID, you don't need them because it is in session.
So remove ?userId=<?php echo $userId; ?> from your action attribute and remove the user_id hidden field.PHP Code:<form name "input" action="new_threads.php?userId=<?php echo $userId; ?>" method="post"></p>
<input type="hidden" name="user_Id" size="25" value="<?php echo $userId; ?>"><br>
oki its working a bit better but in new_threads.php its not putting the new topic through can you check my code there something wrong with the query syntax:
PHP Code:<!-- Link to CSS-->
<link rel="stylesheet" type="text/css" href= "CSS/default.css" title="Main">
<?php
session_start();
// connect to database
$mysqli = mysqli_connect("localhost", "root","","forum");
// php string query insert into table
$myquery = "insert into threads
values ('','{$_SESSION['userID']}','{$_POST['title']}','{$_POST['date']}'}";
// function which runs the myquery string
$result = mysqli_query($mysqli,$myquery);
// if's statments for inerting data into table
If ($result==true)
{
echo "New Thread Added";
include "threads.php";
}
else
{
echo "Corrupt Thread";
include "threads.php";
}
// close connection with database
mysqli_close ($mysqli);
?>


First thing to do is add var_dump($_POST,$_SESSION); above your $myquery statement. See what it outputs, as one or several of those values are not matching your code.
its coming up with this
its not putting the thread through because of the userID from users table isnt being automatically entered into the query compared to manually inputting it in.array (size=2)
'title' => string 'New Topic' (length=9)
'date' => string '2012/5/4' (length=8)
array (size=1)
'userID' => null
Corrupt Thread


Verify your index.php has session_start(); at the top of it, because it isn't storing your userID into the session.
Yh i have the session_start(); at the top but still not working:
index.php
All thats happening is that in index.php its getting the username and password from my index.html via thePHP Code:<!-- Link to CSS-->
<link rel="stylesheet" type="text/css" href= "CSS/default.css" title="Main">
<?php
session_start();
$mysqli = mysqli_connect("localhost","root","","forum");
$query = "select * from users where username = '$_POST[username]' and password = '$_POST[password]'";
$result = mysqli_query($mysqli,$query);
$_SESSION['userID'] = $_POST['username'];
if (mysqli_num_rows($result) == 0)
{
echo "User Not Found";
include "index.html";
}
else
{
echo "<h3>User Logged in</h3>";
include "threads.php";
}
mysqli_close($mysqli);
?>and then if the post super globals matchs whats in the users table in mysql then it will display user logged in otherwise user not found which is what this piece of code does.PHP Code:'$_POST[username]' and password = '$_POST[password]'"
I need the session to store the userID not the username so i was think like you said before have it asPHP Code:$_SESSION['userID'] = $_POST['username'];
if (mysqli_num_rows($result) == 0)
{
echo "User Not Found";
include "index.html";
}
else
{
echo "<h3>User Logged in</h3>";
include "threads.php";
}
so then have another query which would be something likePHP Code:$_SESSION['userID'] = $userID;
THis wont work because the syntax inst correct.PHP Code:$username = '$_POST[username]'
$password = '$_POST[password]'
$userID = "select 'users'.userID from users where userID = $username AND $password";


Ah, you are close though
PHP Code:<!-- Link to CSS-->
<link rel="stylesheet" type="text/css" href= "CSS/default.css" title="Main">
<?php
session_start();
$mysqli = mysqli_connect("localhost","root","","forum");
$query = "select userID from users where username = '$_POST[username]' and password = '$_POST[password]'"; // updated this line
$result = mysqli_query($mysqli,$query);
if (mysqli_num_rows($result) == 0)
{
echo "User Not Found";
include "index.html";
}
else
{
$row = mysqli_fetch_array($result); // added this line
$_SESSION['userID'] = $row['userID']; // added this line
echo "<h3>User Logged in</h3>";
include "threads.php";
}
mysqli_close($mysqli);
?>
oki ive tried that but its not putting the thread in the table ive tired doing this have a look:
threads.php ive added back the userID and hidden it but changed the value to:
And in the new_threads.php ive left the query string like this:PHP Code:<input type="hidden" name="userID" value="<?php $_SESSION['userID']?>" /><br>
It supposed to say New thread add it seems the coding is working but its not saying new thread added because the query inst getting the user ID.PHP Code:var_dump($_POST,$_SESSION);
$myquery = "insert into threads
values ('','{$_POST['userID']}','{$_POST['title']}','{$_POST['date']}'}";
Keeps coming up with
array (size=3)
'userID' => string '' (length=0)
'title' => string 'Topic Name' (length=10)
'date' => string '2012/4/5' (length=8)
array (size=1)
'userID' => string '1' (length=1)
Corrupt Thread


From what I can tell, you should be able to use $_SESSION['userID'] instead of $_POST['userID'], as if that var_dump() is the $_POST, $_SESSION data, then the session has the userID.
For whatever reason, your threads.php isn't able to get the $_SESSION data by itself, but your new_thread.php can. My guess is threads.php doesn't have session_start();
oki im using the $_SESSION['userID'] instead of $_POST['userID'] if i remove thefrom thread.php and add the session_start(); into it so it looks like this:PHP Code:<input type="hidden" name="userID" value="<?php $_SESSION['userID']?>" /><br>
It still doesnt work its coming up this errorPHP Code:<?php
session_start();
$mysqli = mysqli_connect("localhost", "root","","forum");
$myquery = "select * from `threads`";
$result = mysqli_query($mysqli,$myquery);
echo "<table>";
while($record = mysqli_fetch_array($result,MYSQL_ASSOC))
{
$threadID = $record["threadID"];
$user_ID = $record["user_ID"];
$title = $record["title"];
$date = $record["date"];
echo "<tr>";
echo "<td>";
echo $threadID;
echo "</td>";
echo "<td>";
echo $user_ID;
echo "</td>";
echo "<td>";
echo "<a href=\"posts.php?threadId=" . $threadID . "\">$title</a>";
echo "</td>";
echo "<td>";
echo $date ;
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
A session had already been started - ignoring session_start() in C:\wamp\www\Forum\threads.php on line 21


Does it insert the new thread? The reason you are getting that warning is your new_threads.php has session_start() and then does an include 'threads.php' which is including a second session_start().
Since you removed the hidden field for userID on threads.php, you can likely remove the session_start() from threads.php as well, as the only page that would need it is, index.php and new_threads.php
oki ive done that just for testing ive removed include thread.php for testing and the code does work however its not echoing new thread added so its not inputing the data into the threads table


add
to your mysqli_query line.PHP Code:or die(mysqli_error($mysqli));
ive tried it i got an error showing
This is the coding for new_threads.phpYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '}' at line 2
PHP Code:<!-- Link to CSS-->
<link rel="stylesheet" type="text/css" href= "CSS/default.css" title="Main">
<?php
session_start();
// connect to database
$mysqli = mysqli_connect("localhost", "root","","forum");
// php string query insert into table
var_dump($_POST,$_SESSION);
$myquery = "insert into threads
values ('','".$_SESSION['userID']."','{$_POST['title']}','{$_POST['date']}'}";
// function which runs the myquery string
$result = mysqli_query($mysqli,$myquery) or die (mysqli_error($mysqli));
// if's statments for inerting data into table
If ($result==true)
{
echo "New Thread Added";
include "threads.php";
}
else
{
echo "Corrupt Thread";
include "threads.php";
}
// close connection with database
mysqli_close ($mysqli);
?>


There we go.
Should be -- notice I changed the very last } to a )PHP Code:$myquery = "insert into threads
values ('','".$_SESSION['userID']."','{$_POST['title']}','{$_POST['date']}'}";
PHP Code:$myquery = "insert into threads
values ('','".$_SESSION['userID']."','{$_POST['title']}','{$_POST['date']}')";
Finally everything works wicked job cpradio thank you sooo much also If oki I just have a couple of questions so i understand how everything is working.
Firstly in index.php
This basically gets the useID from the users table by running the $mysqli,$query and puts the variable into the session variable. I'm I right ?PHP Code:session_start();
$row = mysqli_fetch_array($result);
$_SESSION['userID'] = $row['userID'];
In threads.php
What is this part ?threadId because I notices that theres a capital I and lower case d however in all my coding I also been using threadID so where did this come from ? another thing about this line of code is I understand >$title< this is hyper linking and the fullstops joins the two things together but what are the backwards slash for "\" there are two of them one before the posts.php and another before the $title why do we need these symbols ?PHP Code:echo "<a href=\"posts.php?threadId=" . $threadID . "\">$title</a>";
In new_threads.php
Why did i need to add the var_dump($_POST,$_SESSION); and what does it actually do with the var_dumo then in brackets the two $_post and $_sesssion is this a funtion and its just running the two $ values in the brackets. Also in the second line of code why did I need to add this to make it work or die (mysqli_error($mysqli) so does this basically give a error message when its not running $mysqli which is the connect to the database.PHP Code:var_dump($_POST,$_SESSION);
$result = mysqli_query($mysqli,$myquery) or die (mysqli_error($mysqli));
In posts.php
Firstly what the difference between $_GET and $_POST because I tried using the post super global and it doesn't work one thing I don't get is in the hidden form thread_Id the value is a php script which uses the GET super global to get the threadID from the threads table. But how does it actually do that is it because of the 3rd and 4th line of code where the query states thread_ID`= '$threadId' and $threadId = (int)$_GET['threadId'];. The whole reason I'm confused about this code was because before the use would manually input the thrad_ID but now its getting it by its self. And last question what does the (int) do and does the GET super global work without the (int) and what did you mean by // sanitize your input!.PHP Code:<form name "input" action="new_posts.php?threadId=<?php $threadId = (int)$_GET['threadId'];echo $threadId; ?>" method="post">
<input type="hidden" name="thread_id" value="<?php $threadId = (int)$_GET['threadId']; echo $threadId; ?>" />
$threadId = (int)$_GET['threadId']; // sanitize your input!
$myquery ="SELECT `postID`, `thread_ID`, `description`, `date` FROM posts WHERE `thread_ID`= '$threadId'";
Sorry about the long questions lol


Spot On! That is exactly correct.
The ?threadId being with a lowercase 'd' or a uppercase 'D' doesn't matter. QueryString variables are case insensitive. So you can use $_GET['threadId'], $_GET['threadID'], $_GET['ThreadID'] and they will all return the same thing. You are passing this variable to posts.php so you can show posts for a specific threadID.
As for the '>$title<', this is just HTML output, a link in HTML consists of an opening <a> that contains an href="" attribute, then the text you want to be as the link, then the closing tag </a>. The end result, is <a href="my url">my text that is shown as a link</a>
As for the backslashes, because the echo statement is in double quotes (allowing us to put php variables within the quotes and they will be automatically parsed), we have to escape any additional double quotes we may need for HTML attributes. Since I needed double quotes for the href attribute, I escaped the double quotes needed for that attribute by using a backslash.
The var_dump was for debugging purposes only. I needed to see what values you were receiving in the $_POST and $_SESSION superglobals, so we could tell if your $_POST data was bad or if the $_SESSION data was bad when we were trying to resolve your issue with creating a new thread.
The 'or die(...)' simply stops any PHP execution and displays the mysqli_error if the mysqli_query fails. Thus giving you an idea why your query was not successful (for example, earlier it reported an issue with the '}').
Okay, first $_GET versus $_POST. First off, $_GET is associated to ALL QueryString variables/values. So anything after the ? in a URL. Think of posts.php?threadID=2, threadID is the name of the variable and 2 is the value, and it would be accessible by $_GET. $_GET is NOT encrypted and is easily accessibly by any user (meaning a user can alter that value by changing the value in the URL). You can also cause a form to use get by using <form action="page to send values to" method="get">. In this scenario, the $_GET['threadId'] is referring to the URL variable seen in your browser address bar, it is not directly related to your tables or queries.
$_POST is mostly associated to form submissions (it is the more common use of form submissions). You will see that in your example, you have <form action="new_posts.php...." method="post">, that is telling the form to use post when submitting the form. Unlike $_GET, if your site is using an SSL certificate, $_POST is protected by the SSL certificate. However, keep in mind, $_POST can still be faked by a user (if they know how).
Finally, sanitize your input basically means, get into the habit that ALL INPUT IS BAD UNTIL YOU VALIDATE IT! For example, I could send the following via the querystring "posts.php?threadID=' OR 1=1 --", without the (int) in front of your $_GET['threadId'], you would be open to a SQL Injection that just let me ask for EVERY post from your table. I could even do worse in many situations. Another technique you can use is mysqli_prepare. Prepared statements allow you to protect yourself from SQL Injections (examples of usage are show at the link)
Don't be sorry. Questions are good. Always ask questions, it is the best way to learn.
Wicked oki so the
Is basically for testing a and error handling purposes.PHP Code:var_dump($_POST,$_SESSION);
$result = mysqli_query($mysqli,$myquery) or die (mysqli_error($mysqli));
And the $_GET['threadId'] is generally used for get variables from the URL in browsers and its not really getting the threadID from the threads table jsut getting it from the URL, so im wondering would it be possible instead of using URL to get the threadID and send it off how about using the actually value of threadID from the threads table.
And this may sound silly but when you say query string what do you mean by that ?


Yes, so you can actually remove the var_dump() line and the or die() piece.
Well, you did. You got it from the threads table to build the URL, the URL then has the threadID in the URL so it can pass that value to the posts.php page. Otherwise, you would have to come up with some other method of passing that data from one page to another, using the URL is a widely accepted solution (look at this forum URL for example, you will see showthread.php?936514-PHP-forum-post-not-working&p=5267461, this forum is passing key fields to the showthread.php file so it can load the appropriate posts for the given thread).
A URL consists of multiple parts, scheme, host, path, and optionally a querystring.
Example: http://mydomain.com/mypath/myfile.php?query=string
The scheme is http://, another scheme would be https://
The host is mydomain.com
The path is /mypath/myfile.php
The QueryString is query=string
The ? is just the character separator designated to separate the path from the query string. It isn't part of the query string and it isn't part of the path.
Oki I understand that we can use the URL to pass the data across and yes I understand that this <?php $threadId = (int)$_GET['threadId'];echo $threadId; ?> script is sending the threadID variable to the '{$_POST['thread_id']}' in the new_posts.php but what I don't understand is say for example that if I click on thread number 2 which is hyper linked and goes to posts.php and in the threads table that ID is "2" how is it passing that variable to the posts.php my understanding is that in threads.phpand then thisPHP Code:$threadID = $record["threadID"];
so im assuming that that part where its saysPHP Code:echo "<a href=\"posts.php?threadId=" . $threadID . "\">$title</a>";
that is basically ?threadId= "what ever the threadID is that the link is corresponding to so you can use ?threadId= "wateve" as a querystring am I right?PHP Code:?threadId=" . $threadID .


Yes, inside the threads.php, it is looping through all of the records in the threads table, reading the threadID from the table and appending it to the URL/hyperlink for the posts.php page, thus passing it via $_GET to the posts.php page in the querystring.
GREAT!!! thanks so much cpradio you been a massive help just out of curiosity are you a professional PHP programmer and is it just PHP which you known about or any other languages ? like C#, C++ etc
Bookmarks