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.
Related
I want to set a url parameter by using uniqid function in php, I get the unique numbers and place them in my database by useing them in a hidden input form. I try to make it so, at the start of the script $number is set to a uniqid which I placed in the hidden input so it will be posted into the database and I can use the same variable to create a href link.
The problem I'm having is that the value stored in my database is not the same as the value stored in the number variable used in the href link which renders the link useless. How do I get both the values equal is there a better way to do what I'm trying to do?
I have tried putting uniqid() in a function
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$number;
} else {
echo "failed";
}
echo $link;
}
html
<html>
<body>
<form method="post" action="home.php">
<input type="text" name="namn"> <br>
<input type="text" name= "efternamn"><br>
<input type="hidden" value="<?php $number ?>" name="hide">
<input type="submit" >
</form>
<br>
</body>
</html>
I get different values on the link that is echoed and the value stored in my database ( I know this form is not secure )
I think you just need to use the $_POST['hide'] value on the link.
It would also be better to echo the link only if it has been created.
Where you have the echo currently, it is possible to echo the $link variable even if it was not been created!
<?php
$servername = "localhost";
$username = "root";
$password = "";
$homeDB = "homeDB";
$conn = new mysqli($servername, $username, $password, $homeDB);
if($conn->connect_error) {
die("failed to connect to server".$conn->connect_error);
}
$number = uniqid();
if(isset($_POST["namn"])) {
$sql = "INSERT INTO information (firstname, lastname, urlID)
VALUES ('".$_POST["namn"]."','".$_POST["efternamn"]."',
'".$_POST["hide"]."')";
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=$_POST[hide]";
// line moved to here
echo $link;
} else {
echo "failed";
}
}
The problem is that when the postback runs, you also run the line $number = uniqid(); again. So the final number which is output is not the one you placed in the hidden field.
Now, you could write
$link = "http://localhost/sqltutorial/execute.php?id=".$_POST["hide"];
and it would output the number which was passed in the POST variable.
Or you could just wait until the postback has happened to generate the unique ID, and use that in both the database call and the output. This saves a) a round-trip for the variable to the browser and back to the server, and b) anyone trying to tamper with the form data. So move the number creation code inside the if:
if(isset($_POST["namn"])) {
$number = uniqid();
...and then replace both references to $_POST["hide"] with $number instead. You can also remove the hidden field from your form.
One final alternative suggestion: Do you even need to do this? I assume your database table has an auto_increment integer field as the primary key? Why not just use the value already being generated by the database as the value for your link?
if($conn->query($sql)== TRUE){
$link = "http://localhost/sqltutorial/execute.php?id=".$conn->insert_id;
would get the auto-generated ID of the last row you inserted and use that in the link instead. See also documentation
I don't see any great purpose in creating a second ID for your row (especially since uniqid() does not promise to always give you a completely unique value), unless you have some specific reason?
So, you want to create a row and redirect on that link after creating.
Steps:
1) First get the next auto increment value for this informations table by this function and store it in $number.
$stmt = $this->db->prepare("SHOW TABLE STATUS LIKE 'informations'");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
$number = $row[10];
}
2) Now do inserting, and after insert you'll get the same autoincrement ID and do everything with that.
Hope, it will help.
NB: You can make a function to grab that auto Increment ID for any table also.
I'm trying to build a relatively simple PHP login script to connect to MySQL database running on my home server. I know the connection works as I've gotten some data returned as I would expect. However, I am having trouble getting the full script to work.
Essentially, I'm taking in a username/password from the user, and I first do a lookup to get the user_id from the users table. I then want to use that user_id value to do a comparison from user_pswd table (i'm storing usernames and passwords in separate database tables). At one point, I was able to echo the correct user_id based on the username input. But I haven't been able to get all the issues worked out, as I'm pretty new to PHP and don't really know where to see errors since I load this onto my server from a remote desktop. Can anyone offer some advice/corrections to my code?
The end result is I want to send the user to another page, but the echo "test" is just to see if I can get this much working. Thanks so much for the help!
<?php
ob_start();
$con = new mysqli("localhost","username","password","database");
// check connection
if (mysqli_connect_errno()) {
trigger_error('Database connection failed: ' . $con->connect_error, E_USER_ERROR);
}
$users_name = $_POST['user'];
$users_pass = $_POST['pass'];
$user_esc = $con->real_escape_string($users_name);
$pass_esc = $con->real_escape_string($users_pass);
$query1 = "SELECT user_id FROM users WHERE username = ?;";
if ($result1 = $con->prepare($query1)) {
$result1->bind_param("s",$user_esc);
$result1->execute();
$result1->bind_result($userid);
$result1->fetch();
$query2 = "SELECT user_pswd_id FROM user_pswd WHERE active = 1 AND user_id = ? AND user_pswd = ?;";
if ($result2 = $con->prepare($query2)) {
$result2->bind_param("is",$userid,$pass_esc);
$result2->execute();
$result2->bind_result($userpswd);
$result2->fetch();
echo "test", $userpswd;
$result2->free_result();
$result2->close();
} else {
echo "failed password";
}
$result1->free_result();
$result1->close();
}
$con->close();
ob_end_clean();
?>
Help with user deletion:
Hello I am creating a user creation system for a project of mine, I am still very new to PHP, my issue is getting the user from the MySQL database and then deleting it, I will show you my code below:
<?php
require_once("config/db.php");
if ($login->isUserLoggedIn() == true) {
if ($_SESSION['user_perm'] == 1) {
//Create Connection
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Check connection
if ($db_connection->connect_error) {
die("Connection failed: " . $db_connection->connect_error);
}
$sql = "SELECT user_name FROM users";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user_name"];
$user_name_delete = $row["user_name"];
$_SESSION['user_name_delete'] = $user_name_delete;
echo 'Delete User<br>';
}
}
}
$db_connection->close(); ?>
On the deleteuser.php page my code is, note this was just a test:
<?php
echo $_SESSION['user_name_delete'];
?>
My issue with this is grabbing the user who you selected to delete as at the moment it only outputs the last user grabbed from the database.
Any help is much appreciated.
This value:
$_SESSION['user_name_delete']
Is going to contain only the last user in your data. Because you keep overwriting it in your loop:
$_SESSION['user_name_delete'] = $user_name_delete;
The short answer is... Don't use session state for this. (Really, you shouldn't use session state for much of anything unless you absolutely have to.) The identity of the user to be deleted should be included in the request to delete the user. In this case, you can add it to the link. Something like this:
echo 'Delete User<br>';
(Or whatever you use to identify the user in the data row.)
Then in deleteuser.php you can get that value from:
$_GET['id']
Validate the inputs, validate that the user is authorized to perform the delete, and then use that value in the WHERE clause of your DELETE query.
Get the users id and insert it into a delete query.
$id = $db->real_escape_string($_GET['id']);
$sql = "delete from users where id = " . $id; and then run the query to delete the user from the database.
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
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.