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

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();
?>

Related

MySQL Show Message If ID Entries Not Found

My original question was not clear enough. SO I'll attempt to give more information. I have a page that pulls data from a database using PHP (default.php). I built this page so that, based on the 'ID' - the content will change on the page. This is because I will have 100+ entries. I don't want to create 100 individual pages since the only the content will be changing.
Example:
https://mywebsite.com/default.php?id=xxxxx1
https://mywebsite.com/default.php?id=xxxxx2
https://mywebsite.com/default.php?id=xxxxx3
etc...
My table have columns for each row including:
'id'
'name'
'image'
'nominations'
etc...
The 'default.php' page is a template that has the following code:
In the header:
<?php
include_once '../dbh.php';
$id = $_GET['id'];
?>
And in the body for each of the columns above:
<?php
$sql = "SELECT nominations FROM channel_info";
$result = mysqli_query($conn, "SELECT nominations FROM channel_info WHERE id='$id'");
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0){
while ($row = mysqli_fetch_assoc($result)) {
echo $row['nominations'];
}
} else {
echo "<p>Sorry. No nominations listed. </p>";
}
?>
etc..
Currently the messages does NOT show when columns in the same row of the table is empty. How can I make this message show so that if it's empty it will display a message? This happens to all the data entries.
Empty column: [screenshot] prnt.sc/tkcw80
Page displa: [screenshot] http://prntscr.com/tk54iv
I'll try to help you but first, could you please tell me what $id is referring to ? $_GET ? $_POST ? ...
it could be a security issue.
So, if you would like to connect to your database I would suggest you to use PHP PDO like so :
define('user', "HERE_YOUR_USER");
define('password', "HERE_YOUR_PASSWORD");
define('DB_name', "HERE_YOUR_DATABASE_NAME");
// REPLACE "localhost:8889" WITH YOUR SERVER:PORT
define('DB_server', "localhost:8889");
try {
$connect = new PDO("mysql:host=".DB_server.";dbname=".DB_name, user, password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
var_dump($e->getMessage());
}
Then, you would like to make a request :
$results = $connect->prepare("SELECT nominations FROM channel_info WHERE id='$id'");
if ($results->execute()) {
while ($r = $results->fetch(PDO::FETCH_ASSOC)) {
echo $r['nominations'];
}
} else {
echo "<p>Sorry. No nominations listed. </p>";
}
Let me know if you have any question about it :)

Use PHP to generate from an existing database for each row a new specific HTML that i already made

First I'm hitting on a wall here and I really could use your help. I coded the database so I have it all up and working plus all the data inside. I worked the HTML and the CSS media print query and I have it how I want it to look exactly. All I have to do now is:
for every row of the mysql select table I have to fill every specific input form
of the html page I made and print it
Can someone give me a hint of how I can do that?
Assuming you want to connect to your database and simply fetch the id you can do the following.
Ensure you change my_host, my_user, my-password, my_databse,my_tablewith your configuration settings. Then if you want to fetch anything else thanid` just change it to the column name you are looking for.
Be aware we are using PHP here.
// Open Connection
$con = #mysqli_connect('my_host', 'my_user', 'my-password', 'my_databse');
if (!$con) {
echo "Error: " . mysqli_connect_error();
exit();
}
// Some Query
$sql = 'SELECT * FROM my_table';
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($query))
{
echo $row['id'];
}
// Close connection
mysqli_close ($con);
Check this link to get a in-depth explanation.
You can do this with two pages. One page gives you the overview and the other page gives you a print preview of your invoice.
The overview:
// DB select stuff here
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>\n";
echo " <td>".htmlspecialchars($row['what'])."</td>\n";
echo " <td>".htmlspecialchars($row['ever'])."</td>\n";
echo " <td>Detail</td>\n";
echo "</tr>\n";
}
The detail page:
$sql = 'SELECT your, columns FROM tab WHERE id = ?';
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$row) {
echo "There is no data for the given Id\n";
return;
}
echo "What: ".htmlspecialchars($row['what'])."<br />\n";
echo "Ever: ".htmlspecialchars($row['ever'])."<br />\n";

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.

How to grab the id of the search result came from

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

How do display SQL search results in separate places

I am using this code to search my sql database, it works but if there are more then one result it will just display them next to each over
Example:
echo "".$row['nick'].""; //would be NAME1NAME2NAME3NAME4
i would like to display
NAME1
MORE INFO
NAME2
MORE INFO
NAME3
MORE INFO
.
<?php
$conn = mysql_connect ("*****", "battlefield", "*****") or die ('I
cannot connect to the database because: ' . mysql_error());
$selected = mysql_select_db ("battlefield")
or die ("Could not select database");
// PHP Search Script
$sql = "SELECT * FROM loadout WHERE nick LIKE '%".$_POST['find']."%'";
$result = mysql_query($sql,$conn)or die (mysql_error());
if (mysql_num_rows($result)==0){
echo "Theres no one here called that!";
}else{
while ($row = mysql_fetch_array($result)){
echo "".$row['nick']."";
}
}
mysql_close();
?>
If you need the html or more info please ask xD
Thanks in advance!
Just add <br> :) !
while ($row = mysql_fetch_array($result)){
echo "".$row['nick']." <a href='link'>MORE INFO</a><br>";
}
Or if you want to display it somewhere else in the page, add all results to ann array and then iterate through them wherever you want:
Store them:
while ($row = mysql_fetch_array($result)){
$results[] = $row['nick']." <a href='link'>MORE INFO</a><br>";
}
Display them:
foreach ($results as $result) {
echo $result;
}

Categories