How to use ? in URL? - php

I am trying to figure out a way to have one PHP page to display all of my blog post but have the URL decide what post is requested from that database. Something kind of like this: localhost/bolg/posts.php?pid=1 In my database I have it set up to where each post has an ID associated with it. So what I want is something that put the pid=1 and put it in the MySQL code. Here is the PHP code of the post.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title, content, date FROM posts where id =3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Assuming you enter example.com?pid=10 in the browser address bar, you can capture that variable pid using the $_GET (docs) array which PHP automatically fills for you when a page is called with a querystring.
Using your existing code as a start point you can
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
if (isset($_GET['pid'])) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, title, content, date FROM posts where id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $_GET['pid']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// output data of each row
// while looop is not necessary, you are only returning one row
$row = $result->fetch_assoc();
echo "<h1> ". $row["title"]. "</h1>". $row["content"]. "" . $row["date"] . "<br>";
}
$conn->close();
} else {
echo "0 results";
}
Notice I took the liberty of amending your database access code to use prepared and parameterised query and binding the values to avoid SQL Injection Attack. You should always use this technique in the future

Related

How do I display data using the url

How do I display the information data using the ID in the url
example is www.thatsite.com/?id=1092
and it will display the data of the 1092 ID
<?php
$connect = mysqli_connect("localhost", "xxxxxxx", "xxxx","xxxx");
$query = "SELECT `name`, `age`, `xxxxx` , `xxxxx`, `image` FROM `profiles` WHERE `id` = $id LIMIT 1";
$id=$_GET['id'];
$result = mysqli_query($connect, $query,$id);
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo $row['xxxx'];x
echo $row['age'];
echo $row['xxxxxxx'];
echo $row['image'];
}
?>
Your code is full of security holes. It is prone to sql injection, xss attack, csrf, html injection.
I have re-written it to circumvent all the issues.
1.) Sql Injection is now mitigated using prepare queries
2.) Html injection is mitigated using intval for integer variables and strip_tags for strings. you can read more about data validations and sanitization in php to see more options available
3.) xss attack has been mitigated via htmlentities().
you can also use htmlspecialchars(). Read more about all this things
see better secured codes below
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ur dbname";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
// ensure that the Id is integer using intval
$id = intval($_GET["id"]);
// if id is a string. you can strip all html elements using strip_tags
//$id = strip_tags($_GET["id"]);
//Avoid sql injection using prepared statement
// prepare and bind
$stmt = $connect->prepare("SELECT name, age , xxxxx, image FROM profiles WHERE id = ? LIMIT 1");
// id is integer or number use i parameter
$stmt->bind_param("i", $id);
// id is integer or number use s parameter
//$stmt->bind_param("s", $id);
$stmt->execute();
$stmt -> store_result();
$stmt -> bind_result($name, $age, $xxxxx, $image);
while ($stmt -> fetch()) {
// ensure that xss attack is not possible using htmlentities
echo "your Name: .htmlentities($name). <br>";
echo "your age: .htmlentities($age). <br>";
echo "your xxxxx: .htmlentities($). <br>";
echo "your image name: .htmlentities($image). <br>";
}
$stmt->close();
$connect->close();
?>
from https://www.w3schools.com/php/php_mysql_select.asp
leave out the 'get id', the id is in the SQL:
$id=$_GET['id'];
The similar example at
https://www.w3schools.com/php/php_mysql_select.asp
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);

Selecting Data from SQL Database Returns "1"

This is my first SQL Database. I've been able to successfully connect to my server and database. But, when I use a query to select data from one of the columns in my table, it returns the number "1". Why is this?
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT Item FROM Items";
$result = $conn->query($sql);
echo "<h1>Connected successfully<h1>";
echo "<p class='lead'>" + $result + "</p>";
$conn->close();
?>
Here's an image of the table named Items
This is what shows up on the webpage where it should echo the contents in the item column:
You're just echoing the whole object, not individual rows. You need to do something like this to iterate over each row.
if ($result = $conn->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo "<p class='lead'>" . $row[0] . "</p>";
}
/* free result set */
$result->close();
}
This is because 2 different things:
You are trying to concat a string with the + simbol not with the . simbol.
Your $result variable contains a mysql_result, because the query was executed.
If you want to echo your data you must to use $result into a while loop.

Getting User Data Based on Their Information

This first field is where a web visitor will enter in the 'cardname' hit submit and be directed to another page (dashboard2.php) where only his or her content will appear.
Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>
The page below is the page that is directed after the user enters in the 'cardname' from the first input field. However, I only want this second page to show the information based on the cardname that was entered. Right now, it shows every single cardname, questionone, answerone from that table.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You have to modify the query to accept a WHERE clause. For instance, WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname']) (The default method for any form is GET unless you specify method="post".).
You should learn about prepared statements for MySQLi and perhaps consider using PDO, it's really not hard.
It seems that you want to perform a search and not a display all the records.
Usually a search returns records that match a certain field, unless a specific ID or unique value was entered in the search. I'm not sure this is the case.
I put this together a little quick but hopefully it helps...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($result->num_rows == 1){
// only one result found, show just that
$row = $result->fetch_assoc()
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}else{
// multiple rows found, show them all
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>

If variable is in db then stop- if variable is not- then enter it

i have been trying to get this script done for a while now - im kind of new to php and mysql but i have been trying to get this to check the db for the username and then if the username exists - stop checking the db and if it doesn't exists add it to the db.
here is my code:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
The problem with your code is that you do the INSERT of the new name inside an if statement that has confirmed the existence of that user already. In addition I think you messed up your SELECT statement by selecting all the users.
Look into INSERT ON DUPLICATE for a better way to do it, or revise your code as below.
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
PLEASE READ I have somewhere to go so I am being lazy so I did not bind the $test variable therefore DO NOT copy and paste this code without updating it to bind the $test variable. Please read this post about PDO and variable binding to prevent SQL injection.
here is my full working code if anyone needs it - it uses the post method - from an html form .... in case some one needs to hack it to pieces for something else
well guys i appreciate all of your help :D but i have found an answer or a way around it i suppose- i thought of it all night and day on how i could make it work and i came up with this
$servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();

mysqli create link based on row

I want to create an link based on row value, AND - MORE IMPORTANT, add an variable - if row empty, then this text... if row have some value, display this....
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be: //web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
This is the base code.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 50";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Label</th><th>URL</th><th>Season</th><th>Episode</th><th>Approved</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
// --------------------------------------------------------------
echo "<td><a href='http://web.com/(VARIABLES HERE)'>";
echo " ".$row["title_id"]."</a></td>";
// --------------------------------------------------------------
//I NEED TO GET THIS DISPLAY:
// if row season is empty, the resulting link must be
// web.com/MOVIES/".$row["title_id"]."
// if row season have some value, then the link must be:
//web.com/SERIES/".$row["title_id"]."/SEASON/".$row["season"]."/EPISODE/".$row["episode"]."
// -----------------------------------------
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
As is stated in the comments, you are using a reserved MySQL keyword: type. So your query is not working properly. You can't tell because you haven't set up any checks to make sure it is working. you can either put backticks around it like so:
SELECT id, `type`
or change the name of the key in your database (I'd recommend this approach, something like titleType). Until you fix this, nothing will work in your PHP.
Once you have fixed this, as for how to generate your results, you could do something like this inside your while loop (I'm assuming your mean the episode value):
if (empty($row['episode'])) {
echo 'web.com/MOVIES/'.$row["title_id"];
}
else {
echo 'web.com/SERIES/'.$row['title_id'].'/SEASON/'.$row['season'].'/EPISODE/'.$row["episode"];
}
THIS IS THE CORRECT FULL CODE.
<?php
$servername = "localhost";
$username = "WRITE YOUR DB username ";
$password = "WRITE YOUR DB password";
$dbname = "WRITE YOUR db name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, label, title_id, season, episode, approved FROM links order by id desc LIMIT 30 OFFSET 1";
$result = $last_id = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table><tr><th>ID</th><th>Audio</th><th>URL</th><th>Temporada</th><th>Episodio</th><th>Aprobado</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["label"]."</td>";
echo "<td><a href=";
if (empty($row['episode'])) {
echo '/peliculas-online/'.$row["title_id"];
}
else {
echo '/series-online/'.$row['title_id'].'/seasons/'.$row['season'].'/episodes/'.$row["episode"];
}
echo ">".$row["title_id"]."</a></td>";
echo "<td>".$row["season"]."</td><td>".$row["episode"]."</td><td>".$row["approved"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

Categories