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.
Related
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!
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.
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'];
I am working on a program that takes HTML code made by a WYSIWYG editor and inserting it into a database, then redirecting the user to the completed page, which reads the code off the database. I can manually enter code in phpmyadmin and it works but in PHP code it will not overwrite the entry in the code column for the ID specified. I have provided the PHP code to help you help me. The PHP is not giving me any parse errors. What is incorrect with the following code?
<?php
//POST VARIABLES------------------------------------------------------------------------
//$rawcode = $_POST[ 'editor1' ];
//$code = mysqli_real_escape_string($rawcode);
$code = 'GOOD';
$id = "1";
echo "$code";
//SQL VARIABLES-------------------------------------------------------------------------
$database = mysqli_connect("localhost" , "root" , "password" , "database");
//INSERT QUERY DATA HERE----------------------------------------------------------------
$queryw = "INSERT INTO users (code) VALUES('$code') WHERE ID = '" . $id . "'";
mysqli_query($queryw, $database);
//REDIRECT TO LOGIN PAGE----------------------------------------------------------------
echo "<script type='text/javascript'>\n";
echo "window.location = 'http://url.com/users/" . $id . "/default.htm';\n";
echo "</script>";
?>
Your problem is that mysql INSERT does not support WHERE. Change the query to:
INSERT INTO users (code) VALUES ('$code')
Then to update a record, use
UPDATE users SET code = '$code' WHERE id = $id
Of course, properly prepare the statements.
Additionally, mysqli_query requires the first parameter to be the connection and second to be the string. You have it reversed. See here:
http://php.net/manual/en/mysqli.query.php
It should also be noted that this kind of procedure should be run before the output to the browser. If so, you can just use PHP's header to relocate instead of this js workaround. However, this method will still work as you want. It is just likely to be considered cleaner if queries and relocation is done at the beginning of the script.
First time question, long time reader :)
I am building forms dynamically from Columns in a MYSQL DB. These columns
are created/ deleted etc.. elsewhere on my App. My form runs a query against a
SQL View and pulls in the column names and count of columns. Simple! build the form,
with the HTML inputs built with a PHP for loop, and it echos out the relevant HTML for the new form fields. All very easy so far.
Now i want a user to update these dynamically added fields and have the data added to the relevant columns - same table
as existing columns. So, as the input fields are named the same as the columns, they are posted to a PHP script for processing.
Problem is, while i have the actual field names inserted in to the SQL INSERT query, i cannot figure out how to extract the POST
data from the POST dynamically and add this to the VALUEs section of the query.
Here is my attempt....
The Query works without the variables added to it.
It works like this, first section/ is to retrieve the columns names from earlier created VIEW - as these are identical to POST names from the form. Then output to array and variable for insertion to Query. It looks like the implode function works, in that the relevant column names are correct in the statement, but i fear that my attempt to inject the column names on to the POST variables is not working.
$custq = "SELECT * FROM customProperties";
$result = $database->query($custq);
$num_rows = mysql_numrows($result);
while (list($temp) = mysql_fetch_row($result)) {
$columns[] = $temp;
}
$query = '';
foreach($columns as $key=>$value)
{
if(!empty($columns[$key]))
{
$values .= "'".'$_POST'."['".$value."'], ";
}
}
$q = "INSERT INTO nodes
(deviceName,
deviceInfo,
".implode(", ", $columns).",
nodeDateAdded,
status
)
VALUES
('" . $_POST['deviceName'] . "',
'" . $_POST['deviceInfo'] . "',
".$values."
CURDATE(),
'1'
)";
$result = $database->query($q)
Any help is much appreciated. I will feed back as much as i can. Please note, relativity new to PHP, so if i am all wrong on this, i will be glad for any tips/ advice
Regards
Stephen
If you want to get the values of every POST input without knowing the input names then you can do it this way:
//get all form inputs
foreach($_POST as $name => $value)
{
echo $name . " " . $value . "<br>";
}
If you want to get the value of certain POST inputs where you know the name of the input field then you can do it this way:
if(isset( $_GET["deviceName"]))
{
$deviceName = $_POST["deviceName"];
}
if(isset( $_GET["deviceInfo"]))
{
$deviceInfo = $_POST["deviceInfo"];
}
To connect to a database and insert the info then you have to do something like this:
$host = "localhost";
$dbuser = "username";
$pass = "password";
$datab = "databasename";
//Create DB connection
$con=mysqli_connect($host, $dbuser, $pass,$datab);
if (mysqli_connect_errno($con))
{
echo "ERROR: Failed to connect to the database: " . mysqli_connect_error();
}
else
{
echo "Connected to Database!";
}
//insert into database
mysqli_query($con, "INSERT INTO nodes (deviceName, deviceInfo) VALUES ('$deviceName', '$deviceInfo')");
(Don't forget to add mysql_real_escape_string to the $_POST lines after you get it working.)