$_SESSION: Undefined Index - php

I'm creating a booking site for meeting rooms.
I have done the sql query to search for free rooms according to the time and date chosen.
This is working. I display the free rooms (in a while loop) in cards with datas from the query.
<?php
if (isset($_POST['submit'])) {
echo '<main role="main">
<div class="card-columns">';
require_once 'connexion_BD.php';
$res_date = $_POST['res_date'];
$res_date = date("Y-m-d", strtotime($res_date));
$res_horaire_id = $_POST['res_horaire'];
$_SESSION['res_date'] = $_POST['res_date'];
$_SESSION['res_horaire'] = $_POST['res_horaire'];
$sql = "SELECT sal_nom, sal_nb_place, sal_notes
FROM salle
WHERE sal_id NOT IN (SELECT res_sal_id FROM reservation WHERE res_date = :res_date AND res_horaire_id = :res_horaire_id)";
$requete = $db->prepare($sql);
$requete->bindValue(':res_date', $res_date);
$requete->bindValue(':res_horaire_id', $res_horaire_id);
$requete->execute();
$i=0;
while ($row = $requete->fetch()) {
$tab_sal_nom[0+$i] = $row['sal_nom'];
$tab_sal_nb_place[0+$i] = $row['sal_nb_place'];
$tab_sal_notes[0+$i] = $row['sal_notes'];
?>
<div class="card bg-light">
<img class="card-img-top" <?php echo 'src="img/salle_reunion_'. rand(1, 8) .'.jpg"' ?> alt="Salle de réunion">
<div class="card-body">
<h5 class="card-title">Salle <?php echo $tab_sal_nom[0+$i]; ?></h5>
<p class="card-text">Salle disposant de <?php echo $tab_sal_nb_place[0+$i]; ?> places.</p>
<p class="card-text"><small class="text-muted">Informations de salle : <?php echo $tab_sal_notes[0+$i]; ?></small></p>
<form action="confirm_resa.php" method="POST">
<button class="btn btn-outline-primary float-right" style="margin-bottom: 15px;" name=<?php echo '"reserver_'.$tab_sal_nom[0+$i].'"'?> type="submit">Réserver</button>
</form>
</div>
</div>
<?php
$i = $i + 1;
}
}
?>
Now here's my problem, I want to know which room name the user choose to store the info in a $_SESSION['sal_choix'], so, I look at the submit button named <?php echo '"reserver_'.$tab_sal_nom[0+$i].'"'?> (equals to reserver_Daum, reserver_Majorelle, reserver_Galle, reserver_Corbin etc...)
My idea was to look with some if:
if (isset($_POST['reserver_Daum'])) $_SESSION['sal_choix'] = "Daum";
elseif (isset($_POST['reserver_Galle'])) $_SESSION['sal_choix'] = "Galle";
etc...
But that's not working, cause in the confirm_resa.php, $_SESSION['sal_choix'] is: undefined index
It's not a session problem because two other : $_SESSION['res_date'] and $_SESSION['res_horaire'] are sets.
I'm pretty sure the problem is in the if(isset($_POST[])) but I can't see it...
help pls!

Related

PHP Search now not returning anything but no errors [duplicate]

This question already has answers here:
PHP SQL STMT SELECT multiple LIKE ? is it possible?
(2 answers)
Closed 2 years ago.
I'm building an online shop (not a real one) using PHP. I have a search results page and a full specs page, the full specs page is working perfectly however when I created a shopping cart page that also works perfectly the search results page no longer returns anything. I have found when commenting out the if statement and while statement the "no items found" message does work but cannot get it to return anything if this is a valid search. After a couple of days, I still cannot figure out what the problem is. I will include the adding to basket and form code as the form is also included on the full specs page which does work. If you can point me in the right direction it would be greatly appreciated.
**Search Bar code**
<?php
global $ConnectingDB;
if (isset($_GET["SearchButton"])) {
}
?>
<form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
<div class="form-group">
<input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
<button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
</div>
</form>
Search Results Code
$db = mysqli_connect("localhost", "root", "", "computerStore") or die (mysqli_error());
require_once("includes/functions.php");
require_once("includes/sessions.php");
include("addingToBasket.php");
?>
<html>
<head>
<title>Search Results</title>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<?php
include("navbar.php");
?>
<div style="height: 15%;"></div>
<div class="container mt-5">
<?php
echo ErrorMessage();
echo SuccessMessage();
?>
<div class="row">
<div class="col-lg-12">
<?php
if (isset($_GET["productNumber"])) {
$Search = $db->real_escape_string($_GET["Search"]);
$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");
$result = new mysqli($db, $sql) or die("bad query: $sql");
$row = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
echo $count;
//stmt = $db->query($sql);
//$row = $stmt->fetchAll();
//echo count($row).' rows selected';
if ($sql->mysqli_num_rows > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$ProductName = $row["productName"];
$ProductNumber = $row["productNumber"];
$ProductType = $row["productType"];
$BriefProductInfo = $row["briefProductInfo"];
$FullProductInfo = $row["fullProductInfo"];
$Image = $row["image"];
$Price = $row["price"];
$Quantity = $row["quantity"];
include("form.php");
}
} else {
?> <div class="container"><h2><?php echo "Item has not been found, please try another search"; ?></h2></div>
<?php
}
}
?>
</div>
</div>
</div>
</body>
</html>
Adding to Basket Code
<?php
if (!(isset($_SESSION['cart']))) {
$_SESSION['cart'] = array();
} else {
echo "";
}
if (isset($_GET['clear'])) {
$_SESSION['cart'] = array();
}
if (isset($_GET['productNumber']) && isset($_GET['quantity'])) {
$ProductNumber = $_GET['productNumber'];
$Quantity = $_GET['quantity'];
if ($Quantity > 0) {
if(isset($_SESSION['cart'][$ProductNumber])) {
$_SESSION['cart'][$ProductNumber] += $Quantity;
} else {
$_SESSION['cart'][$ProductNumber] = $Quantity;
$_SESSION["SuccessMessage"] = "Item has been successfully added to your basket, feel free to continue shopping if there are more items to wish to purchase. However if you
do wish to buy now, amend the item quantity or you added the item by mistake and wish to remove it, please select the view basket link.";
}
}
}
?>
The Form
while ($row = mysqli_fetch_assoc($result)) {
?>
<h2 class="mb-5"><?php echo $row["productName"] ?> - <?php echo $row["briefProductInfo"] ?></h2>
<p class="text-center mb-5"><?php echo $row["productNumber"] ?></p>
<img class="img-fluid mx-auto d-block mt-5 mb-5" src="images/<?php echo $row["image"] ?>" alt="Product Image">
<p style="text-align: justify;"><?php echo $row["fullProductInfo"] ?></p>
<h1 class="mt-5 mb-5" style="color: red;">£<?php echo $row["price"] ?></h1>
<p style="text-align: center;" id="numberAvailable"><?php echo $row["quantity"] ?> Available</p>
<form method="get" action="<?php $_SERVER["PHP_SELF"] ?>">
<div class="row mt-5 mb-5">
<div class="col-lg-2">
<p style="font-size: 170%;" id="numberRequested">Quantity</p>
</div>
<div class="col-lg-2 mt-1">
<select class="pt-2 pb-2" name="quantity" class="form-control" id="numberRequestedPulldown">
<?php
if ($row["quantity"] >= 5) {
for ($i = 1; $i <= 5; $i++) {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
} else {
for ($i = 1; $i <= $row["quantity"]; $i++) {
?> <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
}
?>
</select>
<input type='hidden' name='productNumber' id='productNumber' value='<?php echo $row['productNumber'] ?>'>
</div>
<div class="col-lg-4 mt-1">
<input type="submit" class="btn btn-success btn-block" id="addToBasketLink" value="Add to Basket">
</div>
<div class="col-lg-4 mt-1">
Return to Items List
</div>
</div>
</form>
<?php
}
?>
Your SQL statement for the search may not be formatted correctly:
$sql = $db->query("SELECT * FROM products WHERE productName LIKE '%$Search%' OR productNumber LIKE '%$Search%' OR briefProductInfo LIKE '%$Search%'");
I can tell you from experience that just placing a double apostrophe(") at the start and including the wildcard(%) in your statement may be the wrong way to go try this:
$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');
This separates the wildcard(%) from the search term that the SQL is looking for. By including the % inside of the statement the SQL statement may run but come up with zero results and move onto your next statement because it is looking for '%book%', when it should be just looking for 'book'. This would give you the "no items found" message, because it moves to the next statement.
This is new information 10/30/2020
You are using the search as your name in this input:
<form class="mt-5" method="GET" action="searchResults.php" style="width: 100%;">
<div class="form-group">
<input class="form-control mb-2" type="text" name="Search" placeholder="Search for Item" value="">
<button class="btn btn-success" name="SearchButton" style="width: 100%;">Search</button>
</div>
</form>
You are not carrying over the productNumber though that I see to get start the statement.
if (isset($_GET["productNumber"])) {
Maybe try doing something like this instead:
$Search = filter_input(INPUT_GET, 'Search');
/*use the preg_replace to remove any special characters*/
$Search = preg_replace('/[^a-zA-Z0-9]/', '', $Search);
echo $Search; /*Just to see if it appears*/
/*instead of if (isset($_GET["productNumber"])) { use */
if($Search != ''){
$sql = $db->query('SELECT * FROM products WHERE productName LIKE "%'.$Search.'%" OR productNumber LIKE "%'.$Search.'%" OR briefProductInfo LIKE "%'.$Search.'%"');
continue with code

Print information from database table in shopping site

I tried my best but I stuck on this problem. Sorry for my bad english.
So here is the situation:
I am trying to make a little shopping site. My database table looks like this:
id pic titel desc price
1 gta5.png Grand Theft Auto 5 A open world game... 49.99
2 cod.png Call Of Duty: MW A Ego-Shooter game... 59.99
3 play4.png Playstation 4 Next-Gen Console... 249.99
4 contr.png Ps4 Controller Next-Gen Equipment... 69.99
On the Database Class file I have some function where I get the column information from the table:
public function getImg(){
while($row = mysqli_fetch_row($this->query)){
return $row[1];
}
}
public function getTitel(){
while($row = mysqli_fetch_row($this->query)){
return $row[2];
}
}
...
With getImg() I will get every information on the pic column like: gta5.png, cod.png etc.
My problem is starting here. I want to print out every column with a for loop on the index.php file. But I can't see any information. Here is the index.php file:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
?>
<img src="image/<?php echo $database->getImg(); ?>"></img>
<h4><?php echo $database->getTitel(); ?></h4>
<h5><?php echo $database->getDesc(); ?></h5>
<h2><?php echo $database->getPrice(); ?>€</h2>
<input type="button" name="submit" value="Buy">
<?php
}
?>
</div>
</div>
</li>
</ul>
But as I said there is nothing. The getTableLength() function is the length of the table (In this case 4). I also tried to print it out one by one like this:
<ul>
<li>
<div class="container">
<div class="content">
<?php
for($i = 0; $i < $database->getTableLength(); $i++){
echo $database->getImg() . "<br>";
}
?>
</div>
</div>
</li>
</ul>
But again failed.. I can see even the br tag but not the information that I want to print out. When I put the echo line before the for loop, then I can see the first index of the column (gta5.png), but I want to have all columns.
Hope to see some solutions. Thanks for any kind of help!
EDIT:
It is working when I write 5 instead of the length function:
for($i = 0; $i < 5; $i++){
echo $database->getImg();
}
But I still want to use that function. The getTableLength() function isn't working as I expected. There is nothing to see when I insert the function. The getTable function looks like this:
public function getTableLength(){
$sql = "SELECT COUNT(*) AS num FROM `$this->table`";
$this->query = mysqli_query($this->connect, $sql);
if($this->query){
$row = mysqli_fetch_assoc($this->query);
return $row['num'];
}
}
When I call it on the index.php file like:
$database->getTableLength();
I can see nothing and everything is gone. It's like buggy.
Fixed. It was to complicated. Think simple and do it better..
Here is the solution:
<?php
$table = $database->getTableName();
$sql = "SELECT * FROM `$table`";
$connect = $database->getConn();
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
?>
<form method="post" action="index.php?action=add&id=<?php echo $row["id"] ?>">
<ul>
<li>
<div class="container">
<div class="content">
<img src="image/<?php echo $row["bild"]; ?>"></img>
<h4><?php echo $row["titel"]; ?></h4>
<h5><?php echo $row["beschreibung"]; ?></h5>
<h2><?php echo $row["preis"]; ?>€</h2>
<input type="hidden" name="hidden_name" value="<?php echo $row["titel"]; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row["preis"]; ?>">
<input type="submit" name="add_to_cart" value="Kaufen">
</div>
</div>
</li>
</ul>
<?php

click dynamic php project title links to get full project details on profile page in php

please help. I am building a website where people can upload their projects. I designed it in such a way that one person can have multiple projects. I am fairly new to php and I know I posted way too much code but I need help
I have been able to make the project titles for each user show dynamically when they login in. The problem I have is how do I make each link load up the page with the full project details. Right now it only shows the first project details no matter what title is clicked. Below is the profile page.
<?php if(isset($login_projectTittle)){
echo "Click to see your projects";
?>
<br><br><br><br><br>
<?php
$query = "SELECT * FROM fullprojectdetails WHERE user_id=$login_id";
if ($result=mysqli_query($connection,$query)){
if($count = mysqli_num_rows($result)){
/* because of the mysqli_fetch_object function the variables have to be $rowe->title (as an object) */
while($rowe = mysqli_fetch_object($result)){
?>
<?php $_SESSION['projectstuff'] = $rowe ->projecttitle; ?>
<?php $_SESSION['projectIdNew'] = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
<br>
<?php
}
/* mysqli_free_result frees p the result in the variable ths allowing for a new one each time */
mysqli_free_result($result);
}
}
}
else {echo "";}
?>
I used POST to send the data to the database.
The page that should load up the full project details is the project page. Contents to be displayed on this page are drawn from the session code which is included in the project page and displayed below
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
require('databaseConnect.php');
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Selecting Database
require('databaseSelect.php');
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User (MYSQL Inner Join used here) took hours to learn
$ses_sql=mysqli_query($connection, "select user.user_emailaddress, user.user_fullname, user.user_id, fullprojectdetails.fileToUpload, fullprojectdetails.projecttitle,
fullprojectdetails.projectcreated, fullprojectdetails.projectcategory, fullprojectdetails.projectcountry, fullprojectdetails.projectdetails,
fullprojectdetails.fundTime, fullprojectdetails.fundinggoal, fullprojectdetails.fileToUpload2, fullprojectdetails.name, fullprojectdetails.biography,
fullprojectdetails.yourlocation, fullprojectdetails.website, fullprojectdetails.fileToUpload3, fullprojectdetails.projectdetails2, fullprojectdetails.accountName, fullprojectdetails.bankName, fullprojectdetails.accountType,
fullprojectdetails.accountNo,fullprojectdetails.user_id, fullprojectdetails.projectid from user inner join fullprojectdetails on user.user_id=fullprojectdetails.user_id where user.user_emailaddress='$user_check'");
//saving variables to be used in every page with session_new included
$row = mysqli_fetch_assoc($ses_sql);
$login_session =$row['user_emailaddress'];
$login_fullname =$row['user_fullname'];
$login_id =$row['user_id'];
$login_projectTittle = $row['projecttitle'];
$login_projectLocation = $row['yourlocation'];
$login_projectCategory = $row['projectcategory'];
$login_projectFundGoal = $row['fundinggoal'];
$login_projectSummary = $row['projectdetails'];
$login_projectWebsite = $row['website'];
$login_projectVideo = $row['fileToUpload3'];
$login_Pic = $row['fileToUpload2'];
$login_projectID = $row['projectid'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectPic = $row['fileToUpload'];
$login_projectFullDet = $row['projectdetails2'];
if(!isset($login_session)){
mysqli_close($connection); // Closing Connection
header('Location: login.php'); // Redirecting To Home Page
}
?>
Below is the project page code
<?php
include('session_new.php');
/*echo $_SESSION['projectstuff'];
if (isset($_POST['profile_btn'])){*/
/* if (isset ($_SESSION['projectstuff'])){
$ses_sql=mysqli_query($connection, "select * from fullproject where projecttitle='{$_SESSION['projectstuff']}");*/
?>
<!DOCTYPE html>
<html>
<body>
<!--require for the nav var-->
<?php require 'logged-in-nav-bar.php';?>
<div id= "upperbodyproject">
<div id= "projectheader">
<h2> <?php echo $login_projectTittle; ?><h2>
</div>
<!-- video and funder div-->
<div id = "vidFundCont">
<div id = "video">
<video width='100%' height='100%' controls> <source src="<?php echo $login_projectVideo ?>" type='video/mp4'>Your browser does not support the video tag.</source></video>
</div>
<div id = "funders">
<p> <strong> 20 </strong> <br> <br><span>funders </span> </p> <br> <br> <br>
<p> </p><br>
<p> <span>funded of N<?php echo $login_projectFundGoal ; ?> </span><p><br> <br> <br>
<p><strong> 15 </strong> <br> <span> <br> days left </span></p><br> <br> <br>
<button id = "projectPageButton"> Fund This Project </button>
</div>
<div id = "clearer"></div>
</div>
<!-- location and project condition -->
<div id = "location">
<p> Location: <?php echo $login_projectLocation ; ?> Category:<?php echo $login_projectCategory ; ?> </p>
</div>
<div id ="projectconditions">
<p> This project will only be funded if N<?php echo $login_projectFundGoal ; ?> is funded before the project deadline</p>
</div>
<div id = "clearer"> </div>
<!--project summary and profile -->
<div id = "nutshell">
<p><?php echo $login_projectSummary ; ?> </p> <br> <br>
<span>Share:</span> &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
</div>
<div id = "projProfile">
<div id = "projProfileTop">
<img src="<?php echo $login_Pic ; ?>" width = "50%" height = "100%">
</div>
<div id ="projProfileBottom">
<br>
<p id = "profileNameStyle"> Name: <?php echo $login_fullname; ?> </p> <br>
<p> Website: <?php echo $login_projectWebsite ; ?> </p> <br>
<p> Email: <?php echo $login_session; ?> </p>
</div>
</div>
<div id = "clearer"> </div>
<!-- about and reward title -->
<div id = "aboutProjH">
<h2> About This Project </h2>
</div>
<div id = "rewardH">
<h2> Rewards For Supporting This Project</h2>
</div>
<div id = "clearer"> </div>
<!--project pic and dynamic rewards-->
<div id = "projPic">
<img src="<?php echo $login_projectPic;?>" width = "100%" height = "100%">
</div>
<div id = "rewardDet">
<br>
<span><?php echo $login_projectFullDet; ?> </span>
</div>
<div id = "clearer"> </div>
<div id = "clearer"> </div>
<!-- project details and empty divs -->
<?php
// code to select content form database and display dynamically in a div
$query = "SELECT * FROM reward WHERE user_id=$login_id";
if ($result=mysqli_query($connection,$query)){
if($count = mysqli_num_rows($result)){
/* because of the mysqli_fetch_object function the variables have to be $rowe->title (as an object) */
while($rowe = mysqli_fetch_object($result)){
?>
<div id = "projDet">
<p> <h2><?php echo "N".$rowe->pledgeAmount. " " . "or more"; ?></h2></p> <br>
<p><span> <br><?php echo $rowe ->title; ?></span></p> <br>
<p> <span><?php echo $rowe ->description; ?></span></p> <br>
<p> <span>Estimated Delivery Time: <br> <?php echo $rowe ->deliverytime . " ". $rowe ->deliveryyear; ?></span></p> <br>
<p> <span><?php echo $rowe ->shippingdetails; ?></p></span> <br>
<p> <span>Number of Rewards Available: <br><?php echo $rowe ->reward1No; ?></span></p>
</div>
<!--<div id = "bsideProjDet">
</div> -->
<div id = "clearer"> </div>
<?php
}
/* mysqli_free_result frees p the result in the variable ths allowing for a new one each time */
mysqli_free_result($result);
}
}
/* display dynamic form */
/*$s_sql=mysqli_query($connection, "SELECT * FROM reward WHERE user_id=$login_id");
$rowe = mysqli_fetch_assoc($s_sql);
?>
<?php echo $rowe['title']; ?><br><br>
<?php echo $rowe['pledgeAmount']; ?><br><br>
<?php echo $rowe['description']; ?><br><br>
<?php echo $rowe['deliverytime']; ?><br><br>
<?php echo $rowe['deliveryyear']; ?><br><br>
<?php echo $rowe['shippingdetails']; ?><br><br>
<?php echo $rowe['reward1No']; ?><br><br> */
?>
<div id = "reportProj">
<button id = "projectPageButton"> Report This Project To Gbedion</button>
</div>
<!--<div id = "bsideReportProj"> </div>-->
<div id = "clearer"> </div>
<!-- </div> -->
</div>
<?php
/*}
}
else {
echo "Select a project";
}*/
?>
<!-- page footer-->
<?php require 'logged-in-footer.php';?>
</body>
</html>
The project Id is the primary key and user id is the foreign key in fullprojectdetails table. If more database details are needed please let me know. Had to abandon this project for a month because of this problem.
First don't store the projectid and project title on a session variable, on the profile page, just create a normal variable and store them on that variable, then when you linking to project.php create a query strings, with the id of the project then with the title of the project, ie Dynamic Project Title I believe when you store the id's of the projects in a session, once you click on one project, the browser will always use that id no matter which project you click next, until you unset/destroy the sessions(logout).
there fore this on profile :
<?php $_SESSION['projectstuff'] = $rowe ->projecttitle;?>
<?php $_SESSION['projectIdNew'] = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
should change to :
<?php $projectstuff = $rowe ->projecttitle; ?>
<?php $projectIdNew = $rowe ->projectid; ?>
<?php echo $rowe ->projecttitle; ?>
Then on projetc.php
you first check if the id isset and also the title, then do your queries
this is how you would do it
project.php
<?php
session_start();
//validate your sessions
if (isset($_GET['projectid']) && isset($_GET['projecttitle'])) {
$currentProjectID = urldecode(base64_decode($_GET['projectid']));
$projectTitle = $_GET['projecttitle'];
?>
<?php
require 'logged-in-nav-bar.php';
?>
<div id= "upperbodyproject">
<div id= "projectheader">
<h2> <?php echo $projectTitle; //from the query string ?></h2>
</div>
<!-- get the details of this project -->
<?php
$query = "SELECT * FROM fullprojectdetails WHERE projectid=$currentProjectID";
// Continue your staff then
?>
</div><!-- upperbodyproject -->
<?php
} else {
echo "could not find project id";
}
?>
Hope this will help point you to the correct direction, I would suggest that you look at mysqli prepared statements, and also at PDO prepared statements.

How can I include an image that is tied to a user's database information?

I've been coding PHP for 2 weeks (it's not pretty) and I have not been able to find the answer to my question. I want an admin type user to be able to fill a form and post it to a page where base level users can view the content. I've gotten all of this to work like a charm, but my dilemma is to allow the admin user to include an image as well. Maybe I just don't know what to search for.
Here is the php code and the form for the admin user page:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
include_once("connection.php");
if (isset($_SESSION['adminid'])) {
$adminid = $_SESSION['adminid'];
$adminemail = $_SESSION['adminemail'];
if ($_POST['submit']) {
$title = $_POST['title'];
$deadline = $_POST['deadline'];
$content = $_POST['content'];
$sql_blog = "INSERT INTO blog (title, deadline, content, logoname) VALUES ('$title', '$deadline', '$content', '$logoname')";
$query_blog = mysqli_query($dbcon, $sql_blog);
echo "<script>alert('Your inquiry has been posted')</script>";
}
} else {
header('Location: index.php');
die();
}
$sql = "SELECT adminid, adminemail, adminpassword, adminname FROM admin WHERE adminemail = '$adminemail' LIMIT 1";
$query = mysqli_query($dbcon, $sql);
if ($query) {
$row = mysqli_fetch_row($query);
$adminname = $row[3];
}
?>
and here is the code for the base level user page: (i commented out the image block where I want the admin's image to be shown.
<main>
<div class="container">
<div class="row topbuffpost">
<h1>business inquiries</h1>
<hr>
<?php
include_once('connection.php');
$sql = "SELECT * FROM blog ORDER BY id DESC";
$result = mysqli_query($dbcon, $sql);
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
$content = $row['content'];
$date = strtotime($row['deadline']);
?>
<div class="col-md-4 col-lg-3">
<div class="card hoverable">
<!-- <div class="card-image">
<div class="view overlay hm-white-slight z-depth-1">
<img src="">
<a href="#">
<div class="mask waves-effect">
</div>
</a>
</div>
</div> -->
<div class="card-content">
<h5> <?php echo $title; ?> <br/> <h6>Deadline |<small> <?php echo date("j M, Y", $date); ?> </small> </h6></h5> <br/>
<p> <?php echo $content; ?> </p>
<div class="card-btn text-center">
Read more
<i class="fa fa-lightbulb-o"></i>&nbsp propose a plan
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</main>
All of this works perfectly, I just can't figure out how to have an image display in the same way as the title, deadline, and content. Youtube wont help either, too much outdated php + I haven't been coding long enough to really work things out on my own.
You can save all user images under a folder (let's call /images/user) and record the file name into database.
if ($_POST['submit']) {
$title = $_POST['title'];
$deadline = $_POST['deadline'];
$content = $_POST['content'];
$logoname = basename($_FILES["fileToUpload"]["logoname"]; // <-- Make sure your form is ready to submit an file
// Update below as per your need.
$target = 'images/users/' . $logoname;
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target);
$sql_blog = "INSERT INTO blog (title, deadline, content, logoname) VALUES ('$title', '$deadline', '$content', '$logoname')";
$query_blog = mysqli_query($dbcon, $sql_blog);
echo "<script>alert('Your inquiry has been posted')</script>";
}
You can then display the image your page
<main>
<div class="container">
<div class="row topbuffpost">
<h1>business inquiries</h1>
<hr>
<?php
include_once('connection.php');
$sql = "SELECT * FROM blog ORDER BY id DESC";
$result = mysqli_query($dbcon, $sql);
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
$content = $row['content'];
$date = strtotime($row['deadline']);
$logoname = 'images/user/' . $row['logoname'];
?>
<div class="col-md-4 col-lg-3">
<div class="card hoverable">
<div class="card-image">
<div class="view overlay hm-white-slight z-depth-1">
<img src="<?php echo $logoname; ?>">
<a href="#">
<div class="mask waves-effect">
</div>
</a>
</div>
</div>
<div class="card-content">
<h5> <?php echo $title; ?> <br/> <h6>Deadline |<small> <?php echo date("j M, Y", $date); ?> </small> </h6></h5> <br/>
<p> <?php echo $content; ?> </p>
<div class="card-btn text-center">
Read more
<i class="fa fa-lightbulb-o"></i>&nbsp propose a plan
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</main>

Dynamically populating a div with data from a MySQL table

Lets say I have a persons table :
forename surname age gender
--------------------------------------------
adam example 90 male
john example 90 male
If I wanted to display this information in separate divs, how could this be done? Say for example the following HTML.
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<!-- adams data here -->
</div>
<div class = "jumbotron">
<!-- johns data here -->
</div>
</div>
</div>
I'm aware on how to query the DB to get the information into PHP variables, I'm just not sure how to dynamically display the data in separate divs.
Below is how I am getting the data
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
echo $row->forename, '<br><br>';
echo $row->surname, '<br><br>';
}
$result->free();
}
}
?>
Just wrap the div inside a loop so you'll print a div for each result row
<?php foreach($result as $r): ?>
<div class = "jumbotron">
<?php echo $r['name'] // Print fields you need ?>
</div>
<?php endforeach; ?>
EDIT: Now I can see your query. Try this:
<?php
if($result = $db->query("SELECT forename,surname FROM users ")){
if($count = $result->num_rows){
while($row = $result->fetch_object()){
?>
<div class = "jumbotron">
<?php echo $row->forename; ?><br><br>
<?php echo $row->surname; ?><br><br>
</div>
<?php
}
$result->free();
}
}
?>
Well Joe, This is a fairly simple problem that has probably been answered before.
I'll use the mysqli class of php
first create a mysqli connection object in a file for best practice then include it in your main script.
<?php
$connection = new mysqli($host_address, $username, $password, $database);
?>
include this in your main script
<?php require "path\to\connection\script"; ?>
<?php
$sql_adam = "SELECT * FROM persons WHERE forename = 'adam'";
$sql_john = "SELECT * FROM persons WHERE forename = 'john'";
$qry1 = $connection->query($sql_adam);
$qry2 = $connection->query($sql_john);
?>
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<?php if ($qry1->num_rows >= 1){
while($adam = $qry1->fetch_assoc()){
foreach ($adam as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
<div class = "jumbotron">
<?php if ($qry2->num_rows >= 1){
while($john = $qry2->fetch_assoc()){
foreach ($john as $column => $data) {
echo "<p>$column : $data </p>";
}
}
}
</div>
</div>
</div>
Your Result should be something like
<div class = "container">
<div class="wrapper">
<div class = "jumbotron">
<p>forename : adam</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
<div class = "jumbotron">
<p>forename : john</p>
<p>surname : example</p>
<p>age : 90</p>
<p>gender : male</p>
</div>
</div>
</div>

Categories