Looping through PHP database with columns that link to specific profiles - php

I have a website where I am getting information of college student profiles on a database and displaying it as a linked collection. When I'm looping through the database I want to give each row a specific link to the profile of the student. Right now I am linking it to "profilePage.html" with generic information but I want it to be correlated with the row the user chose on the last(college) page.How do I save/transfer that information to the page. I do not want multiple profile pages but one template that is filled with the user previous choice.
<?php
$result = mysql_query("SELECT * FROM student_info WHERE college='Boston College'", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
?>
<a href="profilePage.html" class="collection-item">
<div class="row summary">
<div class="col s4 center">
<img class = "profile-pic" src="img/defaultProfile.jpg">
</div>
<div class="col s8">
<div class="title"> <?php echo $row[student_Name]; ?> </div>
<div class="black-text condensed thin"><i class="tiny material-icons">today</i> Founder, CEO at Linkle since January 1st, 2015</div>
<div></div>
</div>
</div>
</a>
<?php } ?>
Key thing, my urls are mysite.com/college.php and have no id's to specify them.
Structure of the Database student_info:
Shows the structure of the database

First, do you have an URL Rewriting ? If not, your target page should be a PHP page, like profilePage.php.
Your link to this page have to include a parameter (Query String) which is, for example, the student's ID :
<a href="profilePage.php?id=<?php echo $row['id'] ?>" class="collection-item">
This type of URL will be generated: profilePage.php?id=36
In profilePHP.php, retrieve the parameter in the Query String :
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
?>
mysql_real_escape_string() is really important, it prevents SQL injections.
After that, you could retrieve the student's informations with a SQL query.
<?php
$idStudent = mysql_real_escape_string($_GET['id']);
$sql = sprintf("SELECT * FROM student_info WHERE id = %s", $idStudent);
$query = mysql_query($sql);
$student = mysql_fetch_object($query);
// you should check if the ID exists, and if there is 1 result
?>
<p>Student name is <?php echo $student['student_Name'] ?></p>
A little advice: mysql_query() will disappear soon, you should take a look at PDO.

Related

PHP reservation system passing specific while loop results to next php page

Making a car rental reservation system for a school project, project is in html/php & SQL. So far the user picks location date/time and car category on page 1, user then searches available cars on page 2. on page 2 the cars are listed and user picks the car they want to rent, the cars are listed in while loop from
the database. there is a reserve button attached to each car so that the user can pick.
Heres my issue how do i pass over the cars details as variables(make, model, class, dailyrate) for what the user picks onto the next php page prompting page. im using $_sessions.
<?php
$sql= "SELECT * FROM vehicles WHERE class='$class'";
$result = mysqli_query($db,$sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) { //beginning of while loop
$_SESSION['make']=$row['make'];
$_SESSION['model']=$row['model'];
$_SESSION['class']=$row['class'];
$_SESSION['dailyrate']=$row['daily_rate'];
?>
<div class="card">
<div class="img">
<img src='../../images/defaultcar.png' width='100' height='100'>
</div>
<div>
Make: <?php echo $row['make']; ?><br>
Model: <?php echo $row['model']; ?><br>
<b>Class: <?php echo $row['class']; ?></b><br>
<div class="price"> <b>$ <?php echo $row['daily_rate']; ?></b>/Per day</div>
</div>
<button class='reserve-btn'>Reserve</button>
</div>;
<?php } //ending bracket of while loop
}
else {
echo "0 results";
}
?>
</div>
I will try to help you through google translate, the easiest way to do it is by adding the car ID in the value of the reserve button, then declare a name for the button and send that ID to the next page, getting there only from another SELECT * FROM CARS WHERE ID =? and get the information

Remove Current Row without ID (PHP, MYSQL, HTML)

I am working on a HTML website. I am using a MySQL Database and PHP.
The concept so far is fairly simple:
The user can add some text onto the site by clicking on an add button - the user gets directed to a page with a dialogue box
When he clicks submit, that text is in the data base.
The PHP code knows: while the data base has entries -> echo the text onto the HTML website (I added a while loop)
Now my next step is to let the user delete the text. I added a trash can glyphicon onto the HTML site. When the user clicks it, I would like for the current row in the table to be removed. Unfortunately nothing happens!
Here's the code:
<?php
$query = " SELECT * FROM Thesis";
$sql = mysqli_query($conn, $query);
$count = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?php echo $row["title"]; ?>
<br>
<!--echo the description -->
<?php echo $row["description"]; ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
</div>
</div>
</div>
<?php };
?>
What am I doing wrong? I know that the main mistake must lie somewhere
in $delquery. But I am lost.
I also know that it would be better to have an ID for each row. But I would like to avoid it, because since we are in a while loop, there must be a way to just delete the current row that the while loop is in, right? That would be my preferred solution.
Lastly, I am very new to programming and not the most elegant programmer yet, please be kind :)
You are going to want a simple ID for your thesis table, something like this:
CREATE TABLE `Thesis` (
`thesis_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
PRIMARY KEY (`thesis_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I would separate out the PHP from the display code, putting the PHP code at the top of your file. For security and better code, I would use bind variables with PDO (instead of mysqli). But sticking with your original code, I would rewrite it like this:
<?php
// Establish the connection
$sql = mysqli_query($conn, $query);
// Delete a specific element
if (isset($_GET['delete_id']) && $_GET['delete_id'] > 0) {
$query = "DELETE FROM Thesis WHERE thesis_id = " . $_GET['delete_id'];
mysqli_query($conn, $query);
}
// Gather all the rows
$query = "SELECT * FROM Thesis";
$count = mysqli_num_rows($sql);
$rows = [];
while ($row = mysqli_fetch_array($sql)){
$rows[] = $row;
}
?>
<?php foreach ($rows as $row): ?>
<div class="box green-box">
<p><div class="center-box-content">
<!--echo the title -->
<?= $row["title"] ?>
<br>
<!--echo the description -->
<?= $row["description"] ?>
</p>
<div class="lower-right-box-content">
<a href="adminview.php?delete=<?= $row['thesis_id'] ?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
</div>
</div>
</div>
<?php endforeach; ?>
The foreach call above is a common PHP shortcut, and the <?= tag will echo back something without having to call echo. The deletion of element using a GET call is not recommended, but for simplicity I'm keeping it in place.
WARNING: BE CAREFUL OF SQL INJECTIONS!!
Now, back to the problem.
First of all, your delete SQL code is run every time a row is inserted, so you will never have rows. First step is to delete
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
Next, you want that certain row to be deleted if the user clicks the trash icon. To do this, you can pass the row ID to a PHP page via <a> or $.ajax, then delete it from that PHP page. However, BE CAREFUL OF SQL INJECTIONS
So you would need on your main page:
[delete icon]
And on your deleteRow.php:
$id=$_GET['id'];
//anti-injection code
mysqli_query($conn,"DELETE FROM Thesis WHERE id='$id'");
<a href="adminview.php">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button">
<?php
$delquery = " DELETE * FROM Thesis";
mysqli_query($conn, $delquery);
?>
</span>
</a>
In above code you deleting all the rows. which is wrong. what you should do is:
<a href="adminview.php?id=<?php echo $row["id"];?>">
<span class="glyphicon glyphicon-trash glyphicon-trash" role="button"></span>
</a>
in adminview.php
if(isset($_REQUEST['id'])) {
$delquery = " DELETE FROM Thesis WHERE id= '".$_REQUEST['id']."' ";
mysqli_query($conn, $delquery);
}

Two query at the same time

Hello first of all what i am doing in , i am coding a website for advertise .
Now what do i need is a help to display a lots of data from two tables of database .
What i have done so far u can check at My project you have to login use (Username : test , password : 123456a) to login , so there is everything is okay except an image image are the same on every ads and i do not find the way to make it right .
So i have a "posts" table with an information about ads and an "images" table with a path of an image this is how its looks like :
and this is my code :
<?php
$userid = $_SESSION["userid"];
$sql = "SELECT * FROM posts WHERE userid='$userid' ";
$res = mysqli_query($connect,$sql);
while ($row = mysqli_fetch_assoc($res)) {
?>
<div id="ads">
<div id="titlepic">
<?php echo $row["title"]; ?><br>
<img src="<?php echo $Photo[0]; ?>" height="100px;">
</div>
<div id="managead">
Edit<br style="margin-bottom: 5px;">
Delete<br style="margin-bottom: 5px;">
Renew
</div>
<div id="dates">
<b>Date Added:</b> <?php echo date('m/d/Y', $row["dateadded"]); ?><br>
<b>Renew Date:</b> <?php if($row["renewdate"] > 0){ echo date('m/d/Y', $row["renewdate"]); } ?><br>
<b>Location:</b> <?php echo $row["location"]; ?><br>
<b>Price:</b> <?php echo $row["price"]; ?><br>
</div>
</div>
<hr width="100%">
<?php
so the question is how to extract and images from other table at the same time or how tu run two query at the same time and get an information from them
your SQL statement needs a JOIN in order to include data from two tables in one query.
$sql = "
SELECT *
FROM posts p
JOIN images i
ON p.id = i.postid
WHERE p.userid='$userid'
";
this result set will be populated with all columns from both tables. now you can access path1 via:
<?php echo $row["path1"]; ?>
while this will work for all of your images, such as $row["path2"], $row["path3"], etc, keep in mind this is a bad design for a many-to-many relationship, so it should be normalized to include a linking table which would hold all of your images.

PHP : $_GET is not retrieving data from MySQL database

I have a blog-type php site with mysql database. This blog have some lessons. There's a table "lessons", which contain id, title, text of lesson, etc.
When I display the last lessons on the main page, it works just right.
I connect to db like this:
<?php
$db = mysql_connect ("localhost", "root", "");
mysql_select_db("kursach", $db);
mysql_query("SET NAMES utf8");
$result = mysql_query ("SELECT title, meta_k, meta_d, text FROM settings
WHERE page='index' ", $db);
$myrow = mysql_fetch_array($result);
?>
and display them using loop:
<?php
$result = mysql_query("SELECT id, title, date, description FROM lessons", $db);
$myrow = mysql_fetch_array($result);
do {
printf ("<div class='right-column-content'>
<div class='right-column-content-heading'>
<a href='lesson_view.php?%s'><h1>%s</h1></a>
<h2>%s </h2>
</div>
<div class='right-column-content-content'>
<p>%s</p>
<div class='button'><a href='lesson_view.php?%s' >Читати далі</a></div>
</div>
</div>", $myrow['id'], $myrow["title"], $myrow["date"], $myrow["description"], $myrow["id"]);
}
while($myrow = mysql_fetch_array($result))
?>
I also have a file for full content of the lesson - lesson_view.php. As you can see at the code above, i send the id of lesson to link to this lesson:
lesson_view.php?%s
$myrow["id"]
In the lesson_view.php I connect to db and get the id like this:
<?php
$db = mysql_connect ("localhost", "root", "");
mysql_select_db("kursach", $db);
mysql_query("SET NAMES utf8");
if (isset($_GET['id'])) {$id = $_GET['id'];}
$result = mysql_query("SELECT * FROM lessons WHERE id = '$id' ", $db);
$myrow = mysql_fetch_array($result);
?>
And use this code to display the data:
<div class="right-column-content">
<div class="right-column-content-heading">
<h1><?php echo $myrow['title'] ?></h1>
<h2><?php echo $myrow['date'] ?> </h2>
<h2><?php echo $myrow['author'] ?> </h2>
</div>
<div class='right-column-content-content'>
<p><?php echo $myrow["text"] ?></p>
</div>
</div>
The problem is, when I try to look the full content of lesson (for exaple, /lesson_view.php?1), it doesn't display any data: no title, no text, nothing. I've tried this query directly at MySQL and it works, so, maybe there's some error in php code that I can't find. Will be thankful for any help.
P.S. I'm a beginner at php.
if you want to have in $_GET id then your link should be instead lesson_view.php?%s -> lesson_view.php?id=%s
for example lesson_view.php?id=5 mean that $id = $_GET['id'] will give 5, $id = 5;
<a href='lesson_view.php?%s'><h1>%s</h1></a>
You did not name the 'id' variable.
Change the links to
<a href='lesson_view.php?id=%s'><h1>%s</h1></a>
The only issue is that your printf() have 5 arguments and you are using only four and fourth one is description that you are using here
<div class='button'><a href='lesson_view.php?%s' >Читати далі</a></div>
Solution is that:
printf ("<div class='right-column-content'>
<div class='right-column-content-heading'>
<a href='lesson_view.php?%s'><h1>%s</h1></a>
<h2>%s </h2>
</div>
<div class='right-column-content-content'>
<p>%s</p>
<div class='button'><a href='lesson_view.php?id=%s' >Читати далі</a></div>
</div>
</div>", $myrow['id'], $myrow["title"], $myrow["date"], $myrow["id"], $myrow["description"]);
Move $myrow["id"] in fourth position you will get the ID as query string.
And also add the id in query string.

Issue with bootstrap grid and mysql response

I have an issue with bootstrap and creating a 4 column responsive grid from a mysql response.
The problem is that if the second mysql query has a variable number of results, it brakes the grid.
Here is my code (where the first query has 9 results and the second query has a variable number of results):
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result)) {?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $row['username'];
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
which gives me this:
enter image description here
instead of this (obviously with many 'Hello world'):
enter image description here
Any help greatly appreciated!
Bootstrap doesn't claim to do any kind of elegant bin-packing on panels with different sizes. You could do some programming or css work to make all your panels the same size.
If that doesn't work for your application, you're going to need a layout library that does bin-packing so these panels of different sizes align properly.
There are a few such libraries available as jQuery plugins.
In this, $row[username] is wrong as it should be $row['username'].
$b = "SELECT * FROM $table_presents WHERE bought_for='$row[username]' OR bought_for='' ORDER BY id";
BTW, I changed your code bit. Please Try this.
<?php
$a = "SELECT * FROM $table_users ORDER BY username";
$result = mysql_query($a);
?>
<div class="container">
<div class="row">
<?php while ($row = mysql_fetch_array($result))
{
$username=$row['username'];
?>
<div class="col-xs-3" style="background-color:aqua;">
<?php echo $username;
$b = "SELECT * FROM $table_presents WHERE bought_for='$username' OR bought_for='' ORDER BY id";
$result_presents = mysql_query($b) or die(mysql_error());
while ($row_presents = mysql_fetch_array($result_presents)) {
?>
<div style="background-color:red;">
Hello world!
</div>
<?php }?>
</div>
<?php }?>
</div>
</div>
[NOTE: Users can inject your SQL commands. Use prepared statements and parameterized queries. For more info, click Prevent SQL Injections

Categories