Trouble having passed GET variable display on target page - php

I'm going crazy here. I have two pages. Page A and Page B. I simply want to set a variable in Page A, pass it to Page B via GET method (URL) and then have code display the variable. I do not get any errors, but the the variable simply will not display. Here is the code:
Page A:
print "" .$name . "<br>";
Page B:
<?php
//db connect info above not shown
$password = "*****";
$usertable = "stories";
$myfield = (int) $_GET['id'];
//Connect to db
mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname);
//Fetch from db
$query = "SELECT * FROM stories where story_id = $myfield";
$result = mysql_query($query);
echo "TEXT: ";
if ($result) {
while($row = mysql_fetch_array($result)) {
$name = $row["story_id"];
echo $name;
}
}
?>
All I get returned is "TEXT:"
But it want it to show "TEXT: 4" (because I know 4 is the story_id from page a. I even see the 4 in the URL of page B being successfully passed, but can't get it to display here.
As a second part of the question, my REAL GOAL is not to simply print the story_id, but rather the story text itself (a paragraph of text). This variable is in the same table called story_text. It seems a pipe dream to get the actual story text to display when I can't even simply have the story_id number print as a test.
Please help!

if your url is
http://mysite.net/page-b?var=".$id ."\"
The variable passed will be $var, not $id
$myfield = (int) $_GET['id']; // WRONG
$myfield = (int) $_GET['var']; // RIGHT

Your statement
$myfield = (int) $_GET['id'];
this should be
$myfield = (int) $_GET['var'];

Related

mysql problem using php when update table

This system is based on invitation codes, if u have a code that is present in the database you can submit the input therefore change a value in a row. There are 2 inputs, 1) Invitation Code (key), if exist in the database the user can submit the value 2)Name (user). I done the following code but it doesn't work, any suggestions?
<?php
//get value pass from form in login.php
$username = $POST['user'];
$password = $POST['key'];
//connect to the server and select database
mysql_connect("localhost", "...","...");
mysql_select_db("...");
// Query the database for user
$result = mysql_query("UPDATE invitation_keys SET name ='$username' WHERE key = '$password'";)
or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if ($row['key'] == $password) {
echo "Login success!!!".$row['key'];
} else {
echo "Failed to login";
}
?>
When you are coding in PHP, var_dump($var) is your best friend.
So the first thing to do here, is to print the query.
You will see, that your $username and $password vars are NULL, because you missed the syntax of $_POST[].
After, you can put in var_dump what you want, and that's why its interesting, because you will debug faster with this.

Unique page for each row in database with PHP

I have been trying to create a unique page for each row in my database. My plan is to create a dictionary.php?word=title url, where I can display the description and title of that specific ID. My datbase is contains id, term_title and term_description.
I'm fresh outta the owen when it comes to PHP, but I've managed to atleast do this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Cannot connect to database." . mysqli_connect_error());
}
if (isset($_GET['id']))
{
$id = (int) $_GET['id'];
$sql = 'SELECT * FROM dbname WHERE id = $id LIMIT 1 ';
}
$sql = "SELECT * FROM terms";
$result = $conn->query($sql);
mysqli_close($conn);
?>
I'm really stuck and I dont know what the next step is, I've added the <a href='dictionary.php?=".$row["id"]."'> to each word I want to be linked, and this is properly displayed in the main index.php file (where all my words are listed with <li>. This is my code for this:
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<a href='dictionary.php?=".$row["id"]."'><li class='term'><h4 class='term-title'>" . $row["term_title"]. "</h4></li></a>";
} else {
echo "No words in database.";
}
?>
How do I create this unique page, only displaying title and description for that id? How do I add ?word= to the url?
Thanks for taking your time to help me.
Update from years later: Please, please use parameters when composing your SQL queries. See Tim Morton's comment.
You're on the right track, and ajhanna88's comment is right, too: you want to be sure to include the right key ("word" in this case) in the URL. Otherwise, you're sending a value without telling the page what that value's for.
I do see a couple other issues:
When you click on one of the links you created, you're sending along $_GET["word"] to dictionary.php. In your dictionary.php code, however, you're searching for your word by "id" instead of by "word". I'm guessing you expect users to search your dictionary for something like "celestial" and not "1598", so try this instead:
if (isset($_GET['word'])) {
$word = $_GET['word'];
$sql = 'SELECT * FROM dbname WHERE word = $word LIMIT 1 ';
}
BUT! Also be aware of a security problem: you were letting the user put whatever they want into your query. Take a look at the classic illustration of SQL injection. To fix that, change the second line above to this:
`$word = $conn->real_escape_string($_GET['word']);`
Another problem? You're looking for the word exactly. Instead, you'll probably want to make it case insensitive, so "Semaphore" still brings up "semaphore". There are plenty of ways to do that. The simplest way in my experience is just changing everything to lowercase before you compare them. So that $word assignment should now look like this:
`$word = $conn->real_escape_string(strtolower($_GET["word"]));`
And your query should look something like this:
`$sql = "SELECT * FROM dbname WHERE word = LOWER('$word') LIMIT 1 ";`
Next! Further down, you overwrite your $sql variable with SELECT * FROM terms, which totally undoes your work. It looks like you're trying to show all the words if the user doesn't provide a word to look up. If that's what you're trying to do, put that line in an else statement.
Your $result looks fine. Now you just have to use it. The first step there is to do just like you did when you tested the connection query (if(!$conn)...) and check to see that it came back with results.
Once you have those results (or that one result, since you have LIMIT 1 in your query), you'll want to display them. This process is exactly what you did when printing the links. It's just that this time, you'll expect to have only one result.
Here's a real basic page I came up with from your code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn=new mysqli($servername,$username,$password,$dbname);
if($conn->connect_errno){
die("Can't connect: ".$conn->connect_error);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Dictionary!</title>
</head>
<body>
<?php
if(isset($_GET["word"])){
$word = $conn->real_escape_string(strtolower($_GET["word"]));
$sql = $conn->query("SELECT * FROM dictionary WHERE word=LOWER('".$word."') LIMIT 1");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
while($row=$sql->fetch_assoc()){
echo "<h2>".$row["word"]."</h2>";
echo "<p>".$row["definition"]."</p>";
}
}
} else {
$sql = $conn->query("SELECT word FROM dictionary");
if(!$sql){
echo "Sorry, something went wrong: ".$conn->error_get_last();
} else {
echo "<p>Here are all our words:</p><ul>";
while($row=$sql->fetch_assoc()){
echo "<li>".$row["word"]."</li>";
}
}
echo "</ul>";
}
?>
</body>
</html>
You should also take care to be consistent in your terminology. For this, my MySQL table had three columns: id, word, and definition. I dropped term since your URLs were using word. In my experience, it's best to keep the same terminology. It avoids confusion when your application gets more complicated.
Lastly, to answer your question about creating separate pages, you can see there that for a simple page like this, you may not need a separate page to display the definitions and the links -- just an if/else statement. If you want to expand what's in those if/else blocks, I'd suggest looking at PHP's include function.
You have a great start. Keep at it!

How to dynamically populate new page with variable set on last page?

I'm new to PHP and am trying to build my a website to display information on TV shows stored in a MySQL DB. I've currently got a webpage that will create a table to display the information in the DB, however I'd like each row to link to a dynamically populated page with more info on each show (also pulling from the DB). My question is how do I get the site to know which link has been clicked and then save that as a variable so it can then be recalled on a new to populate the correct information?
I'm currently using this to populate the page.
<!--Populate page with data from SQL-->
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "media_server";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th></th><th></th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
<tr>
<td>
<img src='../images/thumbnails/tv/".$row["thumbnail_path"]."'>
</td>
<td class='td_title'>
<a href='#' onclick='show_var_set();'>".$row["show_title"]."</a>
</td>
<td class='td_desc'>".$row["show_desc"]."</td>
</tr>";
}
echo "</table>";
} else {
echo "Error - 0 results were returned my the database. Please try again.";
}
$conn->close();
?>
One option is to change your href links to point to this page and pass a GET variable you can retreive. The added bonus to this approach is you could bookmark a particular show and come back to that page, since the bookmark will include that GET variable.
So you could change your links to something like this:
echo '', $row['show_title'],'';
Then you'd retrieve that variable by testing for, then reading the GET variable and performing a db query to populate the page with that show's data.
Here's how you'd test for and retreive that variable:
if (isset($_GET['show']))
{
$show = $_GET['show'];
// Perform database lookup using $show
}
Remember to never put user input directly into a query, but use prepared statements and bind the user data to avoid the risk of SQL injection.
There are many ways to pass values from page to page but one is to use session variables:
//Include this at the top of your php scripts that use session variables
session_start();
$_SESSION['your_variable_name_here'] = value_you_want_to_store;
Then on the page you would like to access this use:
$someVariable = $_SESSION['your_variable_name_here'];
Change the SQL to return the show_id,
$sql = "SELECT show_id, show_title, show_desc, thumbnail_path FROM tv_shows WHERE status = 'Y'";
and use that as a parameter to the show_var_set() function.
<a href='#' onclick='show_var_set(".$row["show_id"].");'>".$row["show_title"]."</a>
The show_var_set() function can then use that parameter to get the details for that show from the database.

SQL WHERE ID carryover

Basically I've created two php papes. One selects my entire table, and displays just date, and id number from it. Each date has a link directing to a display.php file. It pulls the ID number with it to the next display.php page. What I want to do on the display.php file is to display the entire row using that PHP.
So I know that Select * from tablename WHERE id=1 will pull that data, but how to get the ID number into there WHERE statement?
This is the main page code:
// SQL query
$strSQL = "SELECT * FROM table1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// DATE
$strName = $row['date'];
// Create a link to display.php with the id-value in the URL
$strLink = "<a href = 'display.php?ID = " . $row['ID'] . "'>" . $strName . "</a>";
// List link
echo "<li>" . $strLink . "</li>";
}
That code links works and goes to display.php.
How would I create the link using the ID number pulling with it. Would I use a post command?
$id= Post['id']
then WHERE id = '$id'
?
TBH I did try that and got nothing. Any suggestions?
USING GET now...still not luck
I've tried the GET statement. In my address bar it shows the ID number. So I see the ID number pulling over with it. I tried even just echoing the ID to see if maybe it was just my code messing up.
<?php
$dbhost = 'localhost';
$dbuser = 'myusername';
$dbpass = 'mypw';
$dbname = 'mydbname';
$id = $_GET['id'];
mysql_connect($dbhost, $dbuser, $dbpass) or die('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbname) or die('Cannot select database. ' . mysql_error());
?>
<body>
ID #<?php echo $id ?>
</body>
</html>
<body>
ID #<?php echo $id ?>
</body>
</html>
Still no luck
So in your display file you'd do something like this
$id = $_GET['ID'];
//DO SANITIZATION ETC ON THE ID HERE TO MAKE SURE ITS SOMETHING WE EXPECTED (AN INT)
$sql = "SELECT STUFF WHERE ID = {$id}"; //FOR BREVITY SAKE DOING AWAY WITH SECURITY
So basically what your first script is doing is passing the id in the url query string, values passed here are accessible in the $_GET super globals array.
Anything you access in here and the other super globals should be treated as completely dangerous to your application. You should filter and escape the hell out of it, and then before inserting it into the database you must escape it using the correct mechanism for your database. Otherwise you leave yourself open to SQL injection attacks.
Values passed in the querystring use GET not POST.
Post is for form variables.
You should also be aware of the danger of a SQL injection attack when taking values from the querystring.

Can you use $_POST in a WHERE clause

There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.

Categories