How to grab the id of the search result came from - php

What you are seeing is my code that displays images as a search result. I have an anchor down there so when you click on the picture it sends you to a TEST page.
I want to have a page set up that will display the rest of the row entries that are associated with that picture:
(Picture) Player: Steve Sax
Card Type: Donruss
Year: 1989
Value: $2.00
How do I grab the "id" in the row of the search result and then echo it in a table that shows up on the TEST page?
<?php
$servername = "*********";
$username = "*********";
$password = "*********";
$dbname = "*********";
$username1=$_SESSION['activeusername'];
$userid = $_SESSION['activeid'];
$userid = $_SESSION['activeid'];
$itemid = $_SESSION['activeid'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM useritems JOIN (users, iteminfo) on (users.id=useritems.UserID AND iteminfo.ID=useritems.ItemID) AND userid='2'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<a href='test1.php'><div id='frame'>
<div id='splash-image' style='background: url(".$row['imagename']."); background-size:cover;'></div>
<div id='text'>
<table >
<tr></tr>
</table>
</div>
</div>";
}
} else {
echo "You Have No Items In Your Closet!!!";
}
mysqli_close($conn);
?>

Pass the id with get as:
echo "<a href='test1.php?id=". $row['id']."'>
And get it on the landing page as:
$id=$_GET['id'];
echo $id;

Assuming the id you want is the item's id, you would echo out
$row['ItemID']
If you wanted to include this ID into your href as a GET parameter you could do something like:
echo "<a href='test1.php?ItemID=" . $row['ItemID'] ."'>...</a>";
Then, in your test1.php, you can retrieve the Item ID for use in your query (after sanitizing it!) by accessing the $_GET global.
$ItemID = $_GET['ItemID'];
If you just wanted the result set row number (not tied to user id or item id), you could echo out something like:
$counter++
or take a look at MySQL - Get row number on select

Related

How to pass the dropdown list selected value from a php form to a mysql query

The function of this web application is to: select a customer from the dropdown list (the dropdown list values are auto popup from the database), it will print the selected customer name and its postcode on the result page.
When I choose the customer name from the dropdown list and click the submit button, the result page only prints the $customerv value (the 1st echo), but the $result value (2nd echo) was not printed. The customer name is unique in the database.
index.php:
<?php
require_once('config.php');
?>
<!DOCTYPE HTML>
<html>
<form action="result.php" method="post">
Customer:<br>
<select Customer id="customer" name="Customer">
<option value="">--- Select Customer ---</option>
<?php
$sql = "SELECT b.BPName from BP b where b.BPCode like 'C%' Order by b.BPName";
$customer = mysqli_query($conn, $sql);
while ($cat = mysqli_fetch_array(
$customer,
MYSQLI_ASSOC
)) :;
?>
<option value="<?php echo $cat['BPName']; ?>">
<?php echo $cat['BPName']; ?>
</option>
<?php
endwhile;
?>
</select>
<input type="submit" value="Submit">
</form>
</html>
config.php:
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$databse = "xxx";
$conn = new mysqli($servername, $username, $password, $databse);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
result.php:
<table>
<?php
require_once('config.php');
$customerv = $_POST['Customer'];
echo $customerv;
$sql = "SELECT shiptozipcode FROM BP WHERE BPName ='$customerv'";
$result = $conn->query($sql);
echo $result;
?>
</table>
The query result itself isn't something that's "printable" to the page. It's not just a single value, it's a complex object. You need to fetch the record(s) from the result. For example:
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
echo $row["shiptozipcode"];
}
If you're sure there will be only one row (it's still a good idea to add some error checking anyway) then you don't need the loop:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["shiptozipcode"];
But either way, you need to extract the data from the result set. (You could also use fetch_object() instead of fetch_assoc() if you prefer object syntax over array syntax.)
As an aside, be aware that your query is wide open to SQL injection. Now would be a good time to learn how to correct that.

I need to dispslay mysql records 10 at a time when I click a link, dynamically

I have read multiple stack overflow answers but still cant find one specific to my needs. Some are outdated. I am using bootstrap and I want to display the first set of records which I am doing by using 'LIMIT 9'. I just have no idea how to get the next 10 records and every 10 records after that to display once the link at the bottom has been clicked. I don't want to open a new page for every 10 records.
`<div class="container-fluid">
<div class="row row-fluid">
<div class="col-xs-12 col-sm-12 col-md-8 offset-md-2 col-lg-8 offset-lg-2">
<h2>List of current Database entries</h2>
<?php
$servername = "localhost";
$username = "xxxxx";
$password = "xxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT 0, 9";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table class='table table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>ID</th><th>Business Name</th><th>Email</th><th>Website</th><th>Phone</th>";
echo "</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>"."id : ". $row["id"]."</td>
<td>".$row["business_name"]."</td>
<td>".$row["email"]."</td>
<td>".$row["website"]."</td>
<td>".$row["phone"]."</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Next 10
</div>
</div>
</div>
That is what I have so far. I would really appreciate some help
This image shows how it looks nowimage of how it looks I dont want people to leave the page for the results. Thank you.
You would usually get a GET/POST parameter specifying current "page".
For example
$page = isset($_GET['page']) ? intval($_GET['page']) : 1; // current page, default is 1
$perPage = 10; // records per one page
$fromLimit = ($page - 1)*$perPage;
$toLimit = $perPage*$page;
$sql = ".... LIMIT $fromLimit, $toLimit";
I have a feeling that you are new to php programming, so be sure to take time and check this:
How to prevent SQL injection
The point is you need a dynamic parameter that you give to a php page so you can dynamically change the content.
Links to your pages would look something like that:
1
2
3
please try to remplace this code:
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT 0, 9";
to:
if ($_GET['pagenum'] > 0){
$a = (int) filter_var($_GET['pagenum'],FILTER_SANITIZE_NUMBER_INT);
}else{
$a = 0;
}
$Startnumber = ($currectid * 10); $limit_read = ($Limit_number + 10);
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT ".$Startnumber .", ".$limit_read ;

Search mysql database and create links from result in php and html

I am a beginner to PHP. I have a database set up with songs in it. At the moment there are only 2 songs and one artist. I am trying to query the database by artist. The page seems to work but is only returning one song instead of two.
I am calling it like this :
search by artist
What is the correct way to do this?
<?php
// get artist id from page call
$artist = $_GET['artist'];
// search by artist
$exists = $mysqli->query("SELECT id FROM songs WHERE artist='$artist'") or die($mysqli->error);
// get numeric array out of result
$Songs = mysqli_fetch_array($exists, MYSQLI_NUM);
foreach($Songs as $key){
echo "<a href='http://www.waylostreams.com/login-system/playSong.php?id=$key&user=$user_id'>Listen</a>";
print "<br>";
}
?>
Thanks in advance for any help!
Sean
This is an example. You can use this code to select all elements in your table(w3schools) nere the link where explain step by step:
https://www.w3schools.com/php/php_mysql_select.asp
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = newmysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

How to use names instead of id's in dynamic webpages

I just started learning php and mysql and i might already be way ahead of myself. The thing i would like to create is a webpage where ppl can sign up for an event, so far so good, the form to submit their first name, last name, age and email adress is working and its actually sending te information to the database.
Next thing i want to create is a page where i can display all the database records submitted (except for the email adress). This is also working, but I wanted to play around with dynamic urls.
When i visit my page http://www.example.com/ppl.php?id=1 i get the information of the first database record displayed but i also wanted to see if i could get this to work with names instead of ids so i tried to edit my code and use http://www.example.com/ppl.php?name=john this does only return an error and however there are a few people called john in the database no records are displayed.
So i would like to know if what i want is actually possible and how do i get this to work with my current code.
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "event";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_GET['id'];
$firstname = 'firstname';
$lastname = 'lastname';
$age = 'age';
$sql = "SELECT * FROM people WHERE id = $id";
$result = $conn->query($sql);
echo "<table id='display' width='600' align='center'>";
echo"<tr><td> Firstname</td> <td> Lastname</td> <td> Age</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<tr><td width='33%'> $row[$firstname]</td> <td width='33%'> $row[$lastname]</td> <td width='33%'> $row[$age] cm</td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Try to change the query:
$sql = "SELECT * FROM people WHERE id = $id";
To:
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name LIKE '%$name%'";
Then echo for each one John you find.
Also consider using CSS like this.
<style>
#display {
width: 600px;
}
#display td {
width: 33%;
}
</style>
You should be looking for two separate $_GET keys: id OR name.
<?php
if (isset($_GET['id'])) {
// logic to get row by ID
} elseif (isset($_GET['name'])) {
// logic to get row by Name
} else {
// logic if no $_GET keys are set
}
I would recommend not using the name field for a find because it's not a primary key in your database - it may not be unique. Your query may return multiple results depending on what data is being stored.
Edit: To answer the question of where to place this in the code sample above, consider placing it where the query string is declared.
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
$sql = "SELECT * FROM people WHERE id = $id";
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$sql = "SELECT * FROM people WHERE name = '$name'";
}
From there you can keep the same query execution logic. But as I stated, I'd advise against using the name field as a key because it may not be unique.

PHP: Display a form only if database value equals X

I have added a form into an admin panel with a yes (1) and no (0) option.
I have changed the Db so that on submit, the value gets added to the Db with the value "seller" 1 or 0, which works fine.
I have a form on my site. I only want it to display to a logged in person if they have a value in the Db of "1" for seller. If they have a value of 0 I want to print a message.
I am guessing I need to query the database, then construct a function and apply it in the page where the form code is to display it if the condition of "1" is met?
I have tried searching but cannot grasp how I can construct it.
<?php
// insert your DB Data
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
mysqli_set_charset($connect, 'utf8');
$query = mysqli_query($connect, "SELECT `seller` FROM `nameTable` WHERE `user` = 'userName'");
$record = mysqli_fetch_array($query);
if($record['seller'] == 1){
echo "Seller is 1";
}else{
echo "Seller is 0";
}
?>
I am using if else condition for my solution here:
<?php
$userLoggedIn = $_SESSION['userName'];//session created while login is stored in variable
//Search table `tbl` for field `SELLER` where field `user` matches with loggedin user
$searchSeller = mysql_query("SELECT `SELLER` from `tbl` WHERE `user`='$userLoggedIn'");
$searchSellerArray = mysql_fetch_array($searchSeller);
//Setting variable to be used in css depending on value in table
if($searchSellerArray['seller']==1){
$displayForm="block";//displays form
$displayMessage="none";//hides message
}
elseif ($searchSellerArray['seller']==0){
$displayForm="none";//hides form
$displayMessage="block";//displays message
}
?>
<form style="display:<?php echo $displayForm;?>;">
//Form content goes here...
</form>
<p style="display:<?php echo $displayMessage;?>;">
//Message content goes here
</p>

Categories