Unique page for each row in database with PHP - 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!

Related

How do I retrieve a specific value from MySQL with PHP?

Okay I'm so fed up. I've spent the better part of my free time for the past week trying to figure this out. I know that the query has changed in SQL but I cant figure it out. All of the other posts I can find seem to be outdated. If anyone could help me out I would really appreciate it.
All I am trying to do is retrieve the id of a row by using a unique "passphrase" that I manually entered into a database and then set that as session data so that I can use that data on other pages. I feel like it shouldn't be this hard.
For demostration purposes here is my code using the older mysql_query.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'test321';
$db = 'local_test';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db); ?>
<?php
include 'includes/connection.php';
$pass = $_POST['inputPass'];
if(!$_POST['submit']) {
echo "please fill out the form";
header ('location: user_authenticate.php');
}
$query = "SELECT id FROM users WHERE pass= '$pass'";
$id = mysql_query($query);
$_SESSION["userId"] = "$id";
print $pass;
print $id;
print $_SESSION["userId"];?>
I've tried a lot of things so I've gotten a lot of different errors. I am hoping someone could point me in the right direction here. What is the best way to do this?
First off, don't use the mysql API; it's deprecated and won't work in PHP 7.
Now that that's out of the way, mysql_query() returns a result set resource (which is like an object) which can contain multiple rows which can contain multiple columns. To access the contents of this resource, you have to fetch a row into an array and then index into that array for the column you want. You need to do something like this:
$query = "SELECT id FROM users WHERE pass= '$pass'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
and then you can use the value of $id.
The same holds for mysqli::query(), which returns a mysqli_result object.

Putting MySQL data from database into a variable

I'm making a luck based website and I want to make sure they have enough spins on their account before they spin.
I did see http://www.w3schools.com/php/php_mysql_select.asp but its not really what I'm looking for.
I have these rows with the names: id username email password spins.
I can deduct amounts from spins but I can't put the exact amount of their spins on a PHP variable to put in a $SESSION for a different page.
Here's how much I have so far.
$numSpin = "SELECT * FROM $tbl_name WHERE spins";
Then put it in a $SESSION
$_SESSION['spinNum'] = $numSpin;
How would I go on to doing this? This does not work as is.
It seems as if you are extremely new to coding so I'll try to help you out.
Here is the code you can use and I'll explain below.
<?php
session_start();
$host = 'localhost'; $db = 'db-name'; $user = 'db-user'; $pw = 'db-pwd';
$conn = new PDO('mysql:host='.$host.';dbname='.$db.';charset=utf8', $user, $pw);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$tbl_name = 'table-name-here';
$un = $username;
$sql = "SELECT * FROM $tbl_name WHERE username=:un";
$query = $conn->prepare($sql);
$query->bindValue(':un', $un, PDO::PARAM_STR);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$totalRows = $query->rowCount();
} catch (PDOException $e) {
die("Could not get the data: " . $e->getMessage());
}
$_SESSION['spinNum'] = $row['name-of-your-field-with-spin-numbers'];
?>
Then...
if($_SESSION['spinNum'] >= 1) {
// allow them to do something
} else {
echo "I'm sorry. It looks like you don't have any spins left. Please try again later.";
}
This code is written using pdo_mysql. You might want to read up on it here.
Line 2 starts your session
Lines 3-5 creates a connection to your database. Make sure to replace "db-name", "db-user" & "db-pwd" with your information.
On line 8 replace "table-name-here" with your database table name
On line 9 you can set "10" to whatever minimum number you want to make sure the account holder has.
On line 19 change "name-of-your-field-with-spin-numbers" to the actual name of the field in your database table that stores the account users available spins.
Now you can use $_SESSION['spinNum'] on your other pages.
Don't forget to use session_start(); at the top of any page where you want to use session variables.

Echo out user information in the same table to their page base on their store information without echoing out the same information to another user

First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.

Why is my Select Statement not working properly?

I am trying to select rows in my table sql. I have done this many times and for this instant it wouldn't work.
Displaying the variable $id, displays correct value, which means it receives a correct value from $_POST however after using it on Select Statement and using mysql_fetch_array, nothing displays.
my code
$id=$_POST['idsend'];
$edit = mysql_query("SELECT * FROM students WHERE id= '$id'") or die(mysql_error());
$fetch=mysql_fetch_array($edit);
echo 'ID= '.$id; ---------> This one displays properly
echo 'ID= '.$fetch['id']; --------> displays nothing
Please help me find out what's wrong. Hehe thanks in advance.
It would be safer to use PDO, to prevent SQL Injection (I made a PDO example of your query):
// it's better to put the following lines into a configuration file!
$host = "enter hostname here";
$dbname = "enter dbname here";
$username = "enter db username here";
$password = "enter db password here";
// setup a PDO connection (needs some error handling)
$db_handle = new PDO("mysql:host=$host;dbname=$dbname;", $username, $password);
// prepare and execute query
$q_handle = $db_handle->prepare("select * from students where id = ?");
$id = $_POST["idsend"];
$q_handle->bindParam(1, $id);
$q_handle->execute();
// get stuff from array
$arr = $q_handle->fetch(PDO::FETCH_ASSOC);
echo $arr["id"];
First of all, you shouldn't use mysql_* functions anymore.
You code fails because mysql_fetch_array() only returns a resource, you need to loop over it to get the actual result.
while ( $row = mysql_fetch_array( $edit ) ) {
printf( 'ID: %s', $row['id'] );
}
Okay, I have found out what's wrong. I apologize for disturbing everyone. I have realized what's wrong in my code and you won't find it on the code I posted in my question.
Carelessness again is the cause for all these. :) hehe
This is where the error is coming from
<form action="" method="post">
<input type="hidden" name="idsend" value="' . $row['id'] . '"/>
I have assigned a variable on a value with extra spaces/character? So the code must look like this.
<input type="hidden" name="idsend" value="'.$row['id'].'"/>
It must be assigned properly to work smoothly with the select statement.
I guess echo-ing the values isn't enough to see if there's something wrong.
Sorry for the trouble.

CMS homepage in php

I am working on something it has 2 pages. One is index.php and another one is admin.php.I am making CMS page where you can edit information on the page yourself. Then it will go to the database, where the information is stored. I also have to have it where the user can update the information on the page. I am getting a little bit confused here.For instance here I am calling the database and I am starting a function called get_content:
<?php
function dbConnect(){
$hostname="localhost";
$database="blank";
$mysql_login="blank";
$mysql_password="blank";
if(!($db=mysql_connect($hostname, $mysql_login, $mysql_password))){
echo"error on connect";
}
else{
if(!(mysql_select_db($database,$db))){
echo mysql_error();
echo "<br />error on database connection. Check your settings.";
}
else{
return $db;
}
}
function get_content(){
$sql = "Select PageID,PageHeading,SubHeading,PageTitle,MetaDescription,MetaKeywords From tblContent ";
$query = mysql_query($sql) or die(mysql_error());
while ($row =mysql_fetch_assoc($query,MYSQL_ASSOC)){
$title =$row['PageID'[;
$PageHeading =$row['PageHeading'];
$SubHeading = $row['SubHeading'];
$PageTitle = $row['PageTitle'];
$MetaDescription =$row['MetaDescription'];
$MetaKeywords = $row['MetaKeywords'];
?>
And then on the index page and I am going to echo it out in the spot that someone can change:
<h2><?php echo mysql_result($row,0,"SubHeading");?>A Valid XHTML and CSS Web Design by WG.</h2>
I do know that the function is not finished I am still working on that part. What I am wondering is am I echoing it out right or I am way off. This is my first time messing with CMS in php and I am still learning it. I am working with navicat and text pad on this, yes I know it is old school but that is what I am being shown with. But my index is a form not a blog. I have seen many of CMS pages for blogs not to many to be used with forms. Any input will be considered thanks for reading my question.
Your question is a bit confusing and your code very incomplete. I'ts hard to say if you do it the right way since I don't see the rest of the script. You need to connect to the database there as well and get your data. The $row variable only exists in the while statement inside you function get_content() though.
You could complete the get_content() and use it in the index.php as well. Remember that the variables you define inside a function only is available there though. If you need the data outside that function you need to return the values you need and save them to some other variable there. Put if you do the same as you've started doing in the get_content() function in index.php, then you just have to echo the variables you define. Like this:
<h2><?php echo $SubHeading; ?></h2>
or you could also do it like this somewhere inside the php tags:
echo '<h2>{$SubHeading}</h2>';
I hope that answers your question.
EDIT:
What you need in the index.php page is exactly what you seem to be doing in the admin file. You need to connect to db using mysql_connect() and select db with mysql_select_db(). You then need to select the data from the db using the appropriate query with $query = mysql_query($sql). If it's more then one row you want to display you need to put it in a while loop otherwise (which seems to be the case here) you just need to do one $row = mysql_fetch_assoc($query). After that you can get the data using $row['column_name']. If you have more than one row you can just use $row['column_name'] in side the while loop to get each consecutive row's data.
Here is an example index.php:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password') or
die('Could not connect: ' . mysql_error());
mysql_select_db('database_name')) or die('Could not select database: ' .
mysql_error());
$sql = "SELECT SubHeading FROM tblContent WHERE PageID='1' LIMIT 1;";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo '<h2>{$row[\'SubHeading\']}</h2>';
mysql_close();
?>
This is just what you need to display the SubHeading from you database. You probably also need to handle your form and save the submitted data to the database in your admin.php file.

Categories