The problem is that i want to change the quantity of the ticket remaining but when i try to submit my input value the code doesn't change the value of mySQL, But at first when the buy button did change the remaining tickets it removed all of them instead of the input value of 1 to 8.
my PHP:
<?php
session_start();
?>
<!DOCTYPE html>
WinterValley | Tickets
<style>
<?php include '../style.css'; ?>
</style>
<?php
try {
// PDO Connection
$serverName = "localhost";
$dbname = "wintervalley";
$dBUsername = "root";
$dBPassword = "";
$charset = 'utf8mb4';
$dsn = "mysql:host=$serverName;dbname=$dbname;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $dBUsername, $dBPassword, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
// Table connection
$stmt = $pdo->prepare("SELECT * FROM `tickets_finland`");
$stmt->execute();
$tickets_finland_data = $stmt->fetchAll();
$total_tickets_finland = $stmt->fetchColumn();
// Database ticket_pop-up content
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['ticketQuantity_finland'])) {
$ticketQuantity_finland = $_POST['ticketQuantity_finland'];
if (is_numeric($ticketQuantity_finland) && $ticketQuantity_finland >= 1 && $ticketQuantity_finland <= 8) {
// Retrieve current quantity
$stmt = $pdo->prepare("SELECT quantity FROM `tickets_finland` WHERE id = :id");
$stmt->bindParam(':id', $tickets_finland_data[0]['id']);
$stmt->execute();
$total_tickets_finland = $stmt->fetchColumn();
// Update the quantity
$new_total_tickets = $total_tickets_finland - $ticketQuantity_finland;
if ($new_total_tickets >= 0) {
$stmt = $pdo->prepare("UPDATE tickets_finland SET quantity = :new_total_tickets WHERE id = :id");
$stmt->bindParam(':new_total_tickets', $new_total_tickets);
$stmt->bindParam(':id', $tickets_finland_data[0]['id']);
$stmt->execute();
} else {
echo "Invalid input: Not enough tickets available";
}
} else {
echo "Invalid input: Enter a number between 1 and 8";
}
}
}
?>
<!-- logo -->
<img src="../img/logo.png" alt="logo" />
<h1>WinterValley</h1>
<!--login/register -->
<?php
if (isset($_SESSION["useruid"])) {
echo '<a class="log-out-button" href="../include/logout.inc.php">Log out</a>';
} else {
include "../include/login.php";
?> <div class="empty2"></div> <?php
include "../include/register.php";
}
?>
<div class="empty3"></div>
</div>
<!-- navbar -->
<?php include "../include/navbar.php" ?>
<!-- Ticket pop-ups -->
<!-- Ticket pop-up (Finland) -->
<div class="ticketPopupBox">
<div class="ticketPopup" id="ticket_pop-up_finland">
<form class="ticketContainer">
<label for="ticketCheckbox">
<h2 class="popup_ticket_title">
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo $ticket_fi['event_id'] . "<br>";
}
?></h2>
</label>
<div class="checkbox_info">
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo "€" . $ticket_fi['ticket_price'] . "<br>";
}
?>
<form method="post" action="../page/tickets.php">
<label for="ticketQuantity">Number of tickets:</label>
<input type="number" id="ticketQuantity_finland" name="ticketQuantity_finland" min="1" max="8" required>
<input type="submit" value="Buy" class="btnTicket">
</form>
<?php
foreach ($tickets_finland_data as $ticket_fi) {
echo $ticket_fi['quantity'] . " Remaining" . "<br>";
}
?>
<div class="ticket_featuring">
<p>Featuring:</p>
<ol>
<li>Sarah Brightman</li>
<li>Ed Sheeran</li>
<li>Kate Bush</li>
<li>Linkin Park</li>
</ol>
</div>
<button type="button" class="btn_cancelTicket" onclick="ticket_closePopupFinland()">Close</button>
</div>
</form>
</div>
</div>
<!-- Ticket info -->
<div class="ticket_box">
<h1 class="ticket_h1">Tickets for Upcoming Events</h1>
<div class="ticket_afstand">
<div class="finland_bg">
<div class="ticket_content">
<h2 class="ticket_head">WinterValley Finland</h2>
<ul>
<li>16:00-00:00</li>
<li>25th February 2023</li>
<li>Eerikinkatu 3, 00100 Helsinki</li>
<div><button onclick="ticket_openPopupFinland()" class="ticket_button">Buy now</button></div>
</ul>
</div>
</div>
</div>
<?php include "../include/footer.php" ?>
<script>
// functie pop-up Finland
function ticket_openPopupFinland() {
document.getElementById("ticket_pop-up_finland").style.display = "block";
}
function ticket_closePopupFinland() {
document.getElementById("ticket_pop-up_finland").style.display = "none";
}
</script>
mySQL code:
CREATE TABLE `tickets_finland` (
`id` int(11) NOT NULL,
`event_id` varchar(255) NOT NULL,
`quantity` int(11) NOT NULL CHECK (`quantity` \<= 2000),
`ticket_price` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
What i want is that if you input a value between 1 to 8 it removes that value from the database.
Related
I am creating a website with MVC architecture and without framework. There are comments like in a blog. I would like to be possible to answer to a comment. But the answer functionnality does not work (when I wanna answer a comment, it is the same as a first comment) and I have difficulties finding why? Could you help me? Here is the adress of the website : cedricjager.com/stream
Here is connection.php:
class Connection {
// Connection
private function getBdd() {
try {
$bdd = ConfigDB::database();
$pdo = new PDO("mysql:host={$bdd['host']}; dbname={$bdd['db_name']}", "{$bdd['username']}", "{$bdd['password']}");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
return $pdo;
}
// Query
public function query($sql, $params = array(), $fetch = null) {
try {
$req = self::getBdd()->prepare($sql);
$req->execute($params);
if ($fetch == 'one') {
return $req->fetch();
} else if ($fetch == 'all') {
return $req->fetchAll();
} else {
return $req;
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
Here is the model :
<?php
require_once 'Connection.php';
class Critics extends Connection{
//Récupère les critiques selon l'id de l'article.
public function findAllById($post_id) {
$sql = "SELECT *, DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date
FROM critics
WHERE id_movie = ?";
$params = [$post_id];
$comms = $this->query($sql,$params,'all');
$critics_by_id = [];
foreach ($comms as $comm) {
$critics_by_id[$comm['id']] = $comm;
}
return $critics_by_id;
}
//Récupèrer les critiques qui ont des enfants.
public function findAllWithChildren($post_id, $unset_children = true) {
$comms = $critics_by_id = $this->findAllById($post_id);
foreach ($comms as $id => $comm) {
if ($comm['parent_id'] != 0) {
$critics_by_id[$comm->parent_id]->children[] = $comm;
if ($unset_children) {
unset($comms[$id]);
}
}
}
return $comms;
}
//récupèrer une critique signalée.
public function findCritics() {
$sql = "SELECT *,DATE_FORMAT(date, '%d/%m/%Y à %H:%i') AS date FROM critics WHERE report=1";
$req = $this->query($sql);
return $req;
}
public function noCritic() {
if ($this->findCritics() == false) {
$msg = '<div class="alert alert-warning">Il n\'y a pas de critiques signalées.</div>';
return $msg;
}
}
//insérer une critique.
public function insertCritic(){
if(isset($_POST['content']) && !empty($_POST['content'])){
$parent_id = isset($_POST['parent_id']) ? $_POST['parent_id'] : 0;
$depth = 0;
if ($parent_id != 0){
$sql = 'SELECT id, depth FROM critics WHERE id = ?';
$params = [$parent_id];
$comm = $this->query($sql,$params, 'one');
if ($comm == false) {
throw new Exception("Ce parent n'existe pas");
}
$depth = $comm->depth + 1;
}
if ($depth >= 3) {
echo "Impossible de rajouter une critique";
}
else {
$sql = 'INSERT INTO critics SET content = ?, author = ?, id_movie = ?, parent_id = ?, date = NOW(), depth = ?';
$params = array($_POST['content'], $_POST['nom'], $_GET['id'], $parent_id, $depth);
$req = $this->query($sql,$params);
}
}
}
}
}
Controller :
public function single() {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$msg = $this->comment->reportCritic();
$this->comment->insertCritic();
$critics = $this->comment->findAllWithChildren($_GET['id']);
$view = require 'Views/single.php';
} else {
header('Location:index.php?p=404');
}
}
Views
<div class="sectioncomments" id="comments">
<?php foreach($critics as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
</div>
<hr>
<div class="row">
<div class="col-lg-12">
<div id="form-comment" class=" panel panel-default formComment">
<div class="panel panel-heading">
<h4>Poster une critique</h4>
<br>
<span class="return"></span>
</div>
<div class="panel panel-body">
<form method="post" class="form-group form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<input type="text" class="form-control" id="nom" placeholder="Votre nom..." name="nom">
</div>
</div>
<div class="form-group">
<div class="col-sm-9">
<textarea class="form-control" id="content" placeholder="Votre critique..." name="content"></textarea>
</div>
</div>
<p class="text-right"><button type="submit" class="btn btn-success">Publier</button></p>
<input type="hidden" name="parent_id" id="parent_id" value="0" >
</form>
</div>
</div>
</div>
</div>
</div>
Comments.php
<div id="comment-<?= $critic['id'] ?>">
<p>
<b><?= $critic['author'] ?></b>
<span class="text-muted">le <?= $critic['date'] ?></span>
</p>
<div class="blockquote">
<blockquote>
<?= htmlentities($critic['content']) ?>
</blockquote>
</div>
<div class="formulaire">
<form class="form-group" method="post">
<p class="text-left">
<input type="hidden" name="valeur" value="<?= $critic['id_movie'] ?>">
<input type="hidden" name="idval" value="<?= $critic['id'] ?>">
<?php if($critic['depth'] <= 1): ?>
<button type="button" class="reply btn btn-default" data-id="<?= $critic['id'] ?>"><i class="fas fa-comments"></i></button>
<?php endif; ?>
<button type="submit" name="signal" class="btn btn-default"><i class="fas fa-bolt"></i></span></button>
</p>
</form>
</div>
</div>
<div id="answer">
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
First, I believe that you never set the children index mentionned in your 'comment.php' view :
<?php if(isset($critic['children'])): ?>
<?php foreach($critic['children'] as $critic): ?>
<?php require('comments.php'); ?>
<?php endforeach; ?>
<?php endif; ?>
Then you should not call two time in a row findAllById for perfomances purpose.
If I where you, maybe I fetch all One time and then build a tree based on what data you get from your query. It allow you to get an infinite nested comments capabilities.
You can do it this way :
$critics = $this->getAllById($id);//movie id
$childs = []; //Will contain all childs indexed by parent_id
$index = []; //will contain all root critics (no parent)
foreach($critics as &$v){
if($v['parent_id'] === 0){ //if no parent, then add to $index
$indexes[$v['id']] = $v;
} else{ //else create an array in $childs at index parent_id
if(!isset($childs[$v['parent_id']])) $childs[$v['parent_id']] = [];
$childs[$v['parent_id']][] = $v;
}
}
//Then you can build your result :
foreach($childs as $id=>&$child){
$parent= $index[$id] ?? $child[$id] ?? null; // search for the parent of the current child
if(is_null($parent)) continue; // a parent doesn't exists anymore, we ignor it, but you can throw an exception instead
if(!isset($parent['children'])) $parent['children'] = [];
$parent['children'][] = $child;
}
return $index;
Now critic should have a 'children' index where are listed all childs. It allow you to build a tree of comments without limit.
All you have to keep in mind, is to correctly set the parent_id when post a new comment.
Let me know if it solves your problem.
I have to pull out the value from the database table call count.php which I already got the value 49. The problem is how to insert into the html
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hopeplace";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT COUNT(*) AS TOTAL_APPLICANT FROM applicant";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo $row["TOTAL_APPLICANT"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
code for the container for the applicant pending
<div class="content">
<div class="row">
<div class="col-xs-5">
<div class="icon-big icon-danger text-center">
<i class="ti-user"></i>
</div>
</div>
<div class="col-xs-7">
<div class="numbers">
<p>Applicant Pending</p>
<p>*this is the place where value need to be put*</p>
</div>
</div>
</div>
<div class="footer">
<hr />
</div>
</div>
You can assign value to one variable and echo that variable inside html
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hopeplace";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$count = 0;
$sql = "SELECT COUNT(*) AS TOTAL_APPLICANT FROM applicant";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$count = $row["TOTAL_APPLICANT"] ;
}
}
mysqli_close($conn);
?>
code for the container for the applicant pending will be like
<div class="content">
<div class="row">
<div class="col-xs-5">
<div class="icon-big icon-danger text-center">
<i class="ti-user"></i>
</div>
</div>
<div class="col-xs-7">
<div class="numbers">
<p>Applicant Pending</p>
<p>
<?php echo $count; ?>
</p>
</div>
</div>
</div>
<div class="footer">
<hr />
</div>
</div>
save both html & php in same file or ensure that your html code is saved as a .php file. So, your script will be - <p><?php echo $total; ?></p> or <p><?= $total ?></p>
I have a database for my ToDo App which has following cloumns:
| ID | ShortDescription | Description | Date | Status |
I already can add a Task to the Datatable and can see it in phphmyadmin.
I have following code till now:
$id = mysql_real_escape_string($_GET['id']);
$out = 'SELECT * FROM ToDo1 WHERE `id` = '.$id.' LIMIT 1';
$result = mysqli_query($link, $out);
$row= mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $row['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $row['Description'];
?>
</div>
<div id= "OutDate">
<?php
echo $row['Date'];
?>
</div>
<div id= "OutStatus">
<?php
echo $row['Status'];
?>
</div>
Now I want to put every ID row on a own Site.
For that I want to make a table of Buttons (Buttonnumber=ID).
On this Button should only be shown the ShortDescription and when I click it I want to go to a the Site which matches to the Button.
Can someone help me?
EDIT
okay thanks now I have this code but it wont work:
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
echo '<p><input type="button" onclick="window.location = All_Groups.php?id=' . $row['ID'] . ' value='.$row['ShortDescription'].' /></p>';
}
I have now following code
<div data-role="page" id="SearchPage" data-title="SearchPage">
<div data-role="header">
<h1>Search</h1>
</div>
<div data-role="content">
<div data-role="header">
<form>
<fieldset data-role="controlgroup" data-type="horizontal" data-mini="true" align="center" id="selectMenu">
<select name="selectStatus" id="selectStatus">
<option value="0">Status</option>
<option value="1">Done</option>
<option value="2">In Progress</option>
</select>
</fieldset>
</form>
</div>
<?php
$dbname= 'Groups';
$dsn = 'mysql:host=localhost;dbname='.$dbname;
$user = 'root';
$pass = '';
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM groups2 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id);
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
?>
<div class="searchwindow">
<?php
$data = $link->query('SELECT * FROM Groups2');
foreach($data as $row) {
$path = $row['ID'];
$description = $row['ShortDescription'];
echo ("<form action='All_Groups.php?id=$path'><button type='submit' value='$description'/>$description</form>" );
}
?>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div><!-- Ende footer -->
</div>
And this is my All_groups.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Unbenanntes Dokument</title>
</head>
<body>
<?php
$servername ="localhost";
$username = "root";
$password = "";
$dbname = "Groups";
$link = mysqli_connect($servername, $username, $password, $dbname);
if (!$link) {
die('Verbindung nicht möglich : ' . mysqli_error($link) );
}
?>
<?php
$row="";
$Date="";
$Status="";
$ShortDescription="";
$Description="";
mysqli_select_db($link, "groups");
?>
</div>
<?php
$id = mysql_real_escape_string($_GET['id']);
$out = "SELECT * FROM groups2 WHERE ID = '$id' ";
$result = mysqli_query($link, $out);
$id = mysqli_fetch_array($result);
?>
<div id= "OutShortDescription">
<?php
echo $id['ShortDescription'];
?>
</div>
<div id= "OutDescription">
<?php
echo $id['Description'];
?>
</div>
<div id= "OutStatus">
<?php
echo $id['Status'];
?>
</div>
<div id= "OutDate">
<?php
echo $id['Date'];
?>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Search</li>
<li>New</li>
<li>More</li>
</ul>
</div><!-- Ende navbar -->
</div>
</body>
</body>
</html>
First of all, don't use the mysql_* methods! Use PDO or mysqli_* instead.
Below, I'm pasting your example query, using PDO:
$dsn = 'mysql:host=localhost;dbname='.$dbname;//$dbName is the name of your database
$user = 'root';
$pass = '123';//use your login information here
$db = new PDO($dsn, $user,$pass);
$query = "SELECT * FROM ToDo1 WHERE id = :id LIMIT 1";
$ps = $db->prepare($query);
$ps->bindParam(':id', $id)
$ps->execute();
$row = $ps->fetch(PDO::FETCH_ASSOC);
Now, to get your button, you don't need to use jquery:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<form action='your/site/$path'><button type='submit' value='$description'/>$description</form>"
?>
Another option is use the onclick:
<?php
$path = $row['ID'];
$description = $row['ShortDescription'];
echo "<input type=\"button\" onclick=\"location.href='your/site/$path'\" value=\"$description\" />";
?>
The \ before " is a escape, so PHP will print the character " and not interpret it as the end of your string.
Advice: Try to avoid mix HTML and PHP, in general this is a bad practice.
<div class = "col-md-9 text-left">
<?php
$host = 'localhost';
$dbname = 'project';
$username = 'root';
$password = '1234';
$charset = 'utf8';
try
{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT subject,description,time,date FROM status";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$usid = ($row['userID']);
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID ORDER BY status.time DESC';
$q1 = $pdo->prepare($sql1);
$q1->execute([$usid]);
$q1->setFetchMode(PDO::FETCH_ASSOC);
}
catch (PDOException $e)
{
die("Could not connect to the database $dbname :" . $e->getMessage());
}
?>
<?php while ($row = $q->fetch()): ?>
<?php while ($row1 = $q1->fetch()): ?>
<div class="col-md-9">
<div class="box box-widget">
<div class="box-header with-border">
<div class="user-block">
<img class="img-circle" src="<?php echo $row10['des']; ?><?php echo $row9['userPic']; ?>" alt="User Image">
<span class="username"><?php echo htmlspecialchars($row1['Fname']); ?> <?php echo htmlspecialchars($row1['Lname']); ?></span>
<span class="description">Shared publicly - <?php echo htmlspecialchars($row['time']) ?> <?php echo htmlspecialchars($row['date']) ?></span>
</div>
<!-- /.user-block -->
<div class="box-tools">
<button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="Mark as read">
<i class="fa fa-circle-o"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="collapse">
<i class="fa fa-minus"></i>
</button>
<button type="button" class="btn btn-box-tool" data-widget="remove">
<i class="fa fa-times"></i>
</button>
</div>
<!-- /.box-tools -->
</div>
<!-- /.box-header -->
<div class="box-body">
<p><b><?php echo htmlspecialchars($row1['subject']) ?></b></p>
<p><i><?php echo htmlspecialchars($row1['description']) ?></i></p>
<?php
// Check connection
$servername = "localhost";
$username = "root";
$password = "1234";
$dbname = "project";
htmlspecialchars($a = $row1['stno']);
$d1 = $row7['userID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM likes WHERE rec = $a";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$GLOBALS['a'] = $row['do'];
}
}
$z4 = $GLOBALS['a'];
if ($d1==$z4)
{
include ("unlikee.php");
}
else
{
include ("likee.php");
}
$conn->close();
?>
<span class="pull-right text-muted"><?php
$con=mysqli_connect("localhost","root","1234","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
htmlspecialchars($a = $row1['stno']);
$sql="SELECT * FROM likes WHERE rec = $a";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("%d\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
</h5>
<span class="description-text"><?php
$con=mysqli_connect("localhost","root","1234","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
htmlspecialchars($a = $row1['stno']);
$sql="SELECT * FROM likes WHERE rec = $a";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
if ($rowcount==1)
echo 'Like';
else
echo 'Likes';
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?> - 3 comments</span>
</div>
<!-- /.box-body -->
<!-- /.box-footer -->
<div class="box-footer">
<form action="#" method="post">
<img class="img-responsive img-circle img-sm" src="../dist/img/user4-128x128.jpg" alt="Alt Text">
<!-- .img-push is used to add margin to elements next to floating images -->
</form>
</div>
<!-- /.box-footer -->
</div>
<!-- /.box -->
</div>
<?php endwhile; ?> <?php endwhile; ?>
</div>
I want to retrieve the Data of only one USER but I don't know how to give a condition for it in SQL Statement. Where and how I can put WHERE userID = $user_Session?
$sql = "SELECT subject,description,time,date FROM status";
In the two code statements above where should I put the first?
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID ORDER BY status.time DESC';
$sql1 =
'SELECT
status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM
status , tbl_users
WHERE
status.userID=tbl_users.userID
AND [correct_table_name].userID = $user_Session # here with AND instead WHERE
ORDER BY
status.time DESC';
Here is the code I added a parameter UID
try
{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = "SELECT subject,description,time,date FROM status";
$q = $pdo->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
$usid = ($row['userID']);
$sql1 = 'SELECT status.subject, status.description, status.time , status.date , status.stno , status.userID , tbl_users.userID , tbl_users.Fname , tbl_users.Lname
FROM status , tbl_users
WHERE status.userID=tbl_users.userID and tbl_users.userID = :UID ORDER BY status.time DESC';
$q1 = $pdo->prepare($sql1);
$q1->bindParam(':UID', $usid, PDO::PARAM_INT); //call with param
$q1->execute();
$q1->setFetchMode(PDO::FETCH_ASSOC);
}
Why my $_SESSION["products"] has been destroy after logged in, How do I keep my $_SESSION["products"] after I logged in?
Add product to cart before logged in.
After logged in my cart is empty.
CODE
login.php
<?php
ob_start();
session_start();
include 'init.php';
require_once 'config.php';
//initalize user class
$user_obj = new Cl_User();
if(!empty( $_POST )){
try {
$user_obj = new Cl_User();
$data = $user_obj->login( $_POST );
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Login Page</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php require_once 'templates/ads.php';?>
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Login</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="email" id="email" type="email" class="form-control" placeholder="Email" autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="loging in....">Login</button>
<br>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot Password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign up
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>
login function in User.php
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT member_id, member_display_name, member_email, member_status, roles_id FROM fm_member where member_email = '$email' and member_pwd = '$password' ";
//$query = "SELECT user_id, name, email, created, roles_id, id FROM users where email = '$email' and password = '$password'"
$result = mysqli_query($this->_con, $query);
$data = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
mysqli_close($this->_con);
if( $count == 1){
$_SESSION = $data;
if($_SESSION['member_status'] == 'Activated') {
$_SESSION['logged_in'] = true;
return true;
} else {
throw new Exception( 'Your account is Deactiavted! <br> Please contact to Adminnistrator for more information.' );
$_SESSION['logged_in'] = false;
}
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
cart_process.php
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
}
//we need to get product name and price from database.
$statement = $mysqli_conn->prepare("SELECT fm_product.p_name, fm_product.p_price, fm_product.p_member_id, fm_product.p_discount, fm_member.member_display_name, fm_member.member_payment, fm_product_image.img_1, shipping_cost.shipping_register,
shipping_cost.shipping_normal, shipping_cost.shipping_ems FROM fm_product LEFT JOIN fm_member ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_product_image ON fm_product_image.p_id_img = fm_product.p_id LEFT JOIN shipping_cost ON shipping_cost.shipping_vendor = fm_member.member_id WHERE p_id=?");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price, $p_member_id, $p_discount, $member_display_name, $member_payment, $img_1, $shipping_register, $shipping_normal,$shipping_ems);
while($statement->fetch()){
$new_product["p_name"] = $product_name; //fetch product name from database
$new_product["p_price"] = $product_price;
$new_product["p_member_id"] = $p_member_id;
$new_product["p_discount"] = $p_discount;
$new_product["member_display_name"] = $member_display_name;
$new_product["member_payment"] = $member_payment;
$new_product["img_1"] = $img_1;
$new_product["shipping_register"] = $shipping_register;
$new_product["shipping_normal"] = $shipping_normal;
$new_product["shipping_ems"] = $shipping_ems;
//fetch product price from database
if(isset($_SESSION["products"])){ //if session var already exist
if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["products"][$new_product['product_code']]); //unset old item
}
}
$_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array
}
$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
//set variables to use them in HTML content below
$product_name = $product["p_name"];
if(!empty($product["p_discount"]))
{
$product_price = $product["p_discount"];
} else if(empty($product["p_discount"])) {
$product_price = $product["p_price"];
}
$product_code = $product["product_code"];
$p_member_id = $product["p_member_id"];
$member_display_name = $product["member_display_name"];
$member_payment = $product["member_payment"];
$product["product_qty"] = 1;
$product_qty = $product["product_qty"];
$cart_box .= "<li>$product_name — Price ".$product_price." x ".$product_qty." = ".sprintf($product_qty * $product_price)."×</li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
$cart_box .= '<div class="cart-products-total" style="border-top: 1px solid #C0C0C0;">'.$quantity.'Total : '.sprintf($total).'<u>Check Out</u></div>';
die($cart_box); //exit and output content
}else{
die("Empty Cart!"); //we have empty cart
}
}
EDIT
home.php added
<?php
session_start();
include('connect.php');
$ID = $_SESSION['member_id'];
if(!isset($_SESSION['logged_in'])){
header('Location: index.php');
}
?>
<?php require_once 'templates/header.php';?>
<?php if($_SESSION['roles_id']=='1') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> Admin Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } else if($_SESSION['roles_id']=='2') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> User Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } ?>
looks like $_SESSION = $data; may be your culprit, you're resetting the entire session variable with data.
EDIT
Where $_SESSION = $data is change it to this;
$data["products"] = $_SESSION["products"];
$_SESSION = $data;