PHP: Display a form only if database value equals X - php

I have added a form into an admin panel with a yes (1) and no (0) option.
I have changed the Db so that on submit, the value gets added to the Db with the value "seller" 1 or 0, which works fine.
I have a form on my site. I only want it to display to a logged in person if they have a value in the Db of "1" for seller. If they have a value of 0 I want to print a message.
I am guessing I need to query the database, then construct a function and apply it in the page where the form code is to display it if the condition of "1" is met?
I have tried searching but cannot grasp how I can construct it.

<?php
// insert your DB Data
$user = "";
$pass = "";
$host = "";
$dbdb = "";
$connect = mysqli_connect($host, $user, $pass, $dbdb);
if(!$connect)
{
trigger_error('Error connection to database: '.mysqli_connect_error());
}
mysqli_set_charset($connect, 'utf8');
$query = mysqli_query($connect, "SELECT `seller` FROM `nameTable` WHERE `user` = 'userName'");
$record = mysqli_fetch_array($query);
if($record['seller'] == 1){
echo "Seller is 1";
}else{
echo "Seller is 0";
}
?>

I am using if else condition for my solution here:
<?php
$userLoggedIn = $_SESSION['userName'];//session created while login is stored in variable
//Search table `tbl` for field `SELLER` where field `user` matches with loggedin user
$searchSeller = mysql_query("SELECT `SELLER` from `tbl` WHERE `user`='$userLoggedIn'");
$searchSellerArray = mysql_fetch_array($searchSeller);
//Setting variable to be used in css depending on value in table
if($searchSellerArray['seller']==1){
$displayForm="block";//displays form
$displayMessage="none";//hides message
}
elseif ($searchSellerArray['seller']==0){
$displayForm="none";//hides form
$displayMessage="block";//displays message
}
?>
<form style="display:<?php echo $displayForm;?>;">
//Form content goes here...
</form>
<p style="display:<?php echo $displayMessage;?>;">
//Message content goes here
</p>

Related

Code stops working after I add a new colunm to Table

The code below a member and guest counter . The code runs perfectly however when I add a simple column (online) to the table active_members the entire code stops working (apart from the active_guests as this a separate table)
I have looked tirelessly trying to catch anything that may be causing this I have included the table screenshot below . I would to had add new column (online)that is a varchar to the table members_online and then query in the if SESSION below for that new column .
Why does the code stop working , Can somebody possible see the cause or solution?
As soon as i remove the online column is code runs perfect again .
$sqlt2 query below is the line I want to index the new online column .
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
//declare variables
$guest_timeout = time() -1 * 60;
$member_timeout = time() -1 * 60;
$guest_ip = $_SERVER['REMOTE_ADDR'];
$time = time();
// if the session is set PUTS THE USER IN MEMBERS TABLE
if(isset($_SESSION['CurrentUser'])){
//if user is logged in
$sqlt = mysqli_query($con,"DELETE FROM active_guests WHERE guest_ip='".$guest_ip."'");
**//I WANT TO ADD TO THE ONLINE COLUMN AND REPLACE A SIMPLE STRING INTO ONLINE**
$sqlt2 = mysqli_query($con,"REPLACE INTO active_members VALUES ('".$_SESSION['CurrentUser']."','".$time."')");
$name = $_SESSION['CurrentUser'] ;
}else{
//if user not in a session PUTS THE USER IN GUESTS TABLE
$sqlt3 = mysqli_query($con,"REPLACE INTO active_guests (guest_ip,time_visited)VALUES ('".$guest_ip."','".$time."')");
}
//execute querys
$sqlt4 = mysqli_query($con,"DELETE FROM active_guest WHERE time_visited < ".$guest_timeout);
$sqlt5 = mysqli_query($con,"DELETE FROM active_members WHERE time_visited < ".$member_timeout);
$sqlt6 = mysqli_query($con,"SELECT guest_ip FROM active_guests");
$sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
$online_guests = mysqli_num_rows($sqlt6);
if(isset($_SESSION['CurrentUser'])){
$sqlt7 = mysqli_query($con,"SELECT username FROM active_members");
if($sqlt7->num_rows){
while($row = $sqlt7->fetch_object())
{
echo '<pre>',$row->username,'</pre>' ;
}
//$result->free();
}
}else{
echo "Login to see members-online list";
}
$online_members = mysqli_num_rows($sqlt7);
?>
// display results
<div class="container">
<p>_________________________</p>
<p>online Guests : <?php echo $online_guests ; ?></p>
<p>online Members : <?php echo $online_members ; ?></p>
</div>
Set column "online"s "Default/Expression" to null, hopefully it'll will work!

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

Add Item Drop Down List

I have a drop down list which i filled with items from my database "mydatabase".
connect.php
<?php
$dbname = 'mydatabase';
$dbuser = 'louie';
$dbpass = '';
?>
mydatabase contains the table 'Users' with 'Name' and 'NameID' column.
index.php
<?php
include ("connect.php");
$mysqli = new mysqli("localhost", $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<div class="label">Select Name:</div>
<select name="names" onchange="change(this.value)">
<option value = "none">---Select---</option>
<?php
$query = "SELECT `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='{".$d['Name']."}'>".$d['Name']."</option>";
}
?>
</select>
<select name="nid" id="nameid">
</select>
In my name column there is two values. Louie and Jane which fills the first dropdown "names". What I want to do is whenever I select the Louie, the second drop down with the id 'nameid' will be filled with the NameID column from my database.
I've got some idea in disabling the second drop down but without the database.
<script>
function change(value) {
if(value=="none")
document.getElementById("nameid").disabled=true;
else
document.getElementById("nameid").disabled=false;
}
</script>
But I don't know how to fill the second dropdown with NameID column by selecting the Louie in first drop down.
try something like this:
var x = document.createElement("OPTION");
x.text = value;
var s = document.getElementById("nameid");
s.add(x);
The trick here is to understand that only PHP can access your database, and that reacting on UI changes is a javascript issue. That means that if you want the nameID on your second dropdown, php first needs to already provide it somewhere, and next you'll need some javascript to actually show it.
This is a possible solution:
<!-- note I changed the function onchange="change(this.value)" to onchange="change(this)"
because this.value is actually not the value.. -->
<select name="names" onchange="change(this)">
<option value = "none">---Select---</option>
<?php
// Select both columns you want to use in PHP
$query = "SELECT `NameID`, `Name` FROM `Users`";
$mysqli = mysqli_query($mysqli, $query);
// I used the value field to hold the id, rather than the name, while the name is shown to the user.
while ($d=mysqli_fetch_assoc($mysqli)) {
echo "<option value='".$d['NameID']."'>".$d['Name']."</option>";
}
// your other code...
?>
<script>
function change(oSelect) {
var value = oSelect.options[oSelect.selectedIndex].value;
var name = oSelect.options[oSelect.selectedIndex].innerHTML;
if(name=="Louie") {
document.getElementById('nameid').innerHTML = "";
for (var i=0; i<oSelect.options; i++) {
document.getElementById('nameid').innerHTML += "<option value='"+oSelect.options[i].value+"'>"+oSelect.options[i].value+"</option>";
}
}
}
</script>

How to check if an order has been placed

I have a pretty simple thing going here. Basic query, but I threw a curve at myself when I decided to go one step further.
Basically it goes like this:
Check if the user entered a value in the form
If not, kick out and display a basic error
If they did then check that value against the database to make sure it is valid/exists
If it's valid/exists, set a session variable and go the order form
If not, kick out and display a basic error
What I want to do now is add another check in there, if the user id exists, then I need to check the order status, if they have already order then I want to kick out and Display a simple message letting them know they have already placed the order and it is being processed. If they have not already ordered then I want to proceed to the order form as above.
The database has a field called "ordered" which has a 1 if they have ordered and a 0 if they haven't ordered yet.
Here is my code that is working, I have tried several things but it keeps blowing up:
<?php
session_start();
$db_host = 'localhost';
$db_username = 'xxxxxx';
$db_password = 'xxxxxxxx';
$db_name = 'xxxxxxxx';
mysql_connect( $db_host, $db_username, $db_password) or die(mysql_error());
mysql_select_db($db_name);
if ($_SERVER['REQUEST_METHOD'] == "POST") {
/** Check whether the user has filled in the text field "employee_id" */
if ($_POST['employee_id'] == "") {
$IdIsEmpty = true;
}else{
$employee_id = $_POST['employee_id'];
if(mysql_num_rows(mysql_query("SELECT employee_id FROM TABLE_2 WHERE employee_id = '$employee_id'"))){
// if userid exists
$_SESSION['emp_id'] = $employee_id;
header('Location: orderform.php');
exit;
}
$IdNotFound = true;
}
}?>
<head>
</head>
<body>
<b>Please enter your Employee ID: </b><br><br>
<form class="" action="index.php" method="post" enctype=
"multipart/form-data" name="test_form" id="test" accept-charset=
"utf-8"><input type="text" name="employee_id">
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdIsEmpty) {
echo ("<br>");
echo ("<b>Enter your employee ID, please!</b>");
echo ("<br>");
}?>
<?php
/** Display error messages if "employee_id" field is empty or if ID does not exist */
if ($IdNotFound) {
echo ("<br>");
echo ("<b>Your employee ID not found!</b>");
echo ("<br>");
}?>
<input type="submit" value="Submit">
</form>
</body>
</html>
Besides swapping out mysql_ functions for mysqli_ like Shivan suggested, you should do this:
Escape any input - you can never trust data provided by users, so do
$employee_id = mysql_real_escape_string($_POST['employee_id']);
In case it is a number, you could also do
$employee_id = intval($_POST['employee_id']);
Just keep this in mind whenever you use input.
Now for your problem:
Simply select your ordered field in the same query:
$order_qry = mysql_query("
SELECT employee_id, ordered
FROM TABLE_2 WHERE employee_id = '$employee_id'
");
if(mysql_num_rows($order_qry)) {
$order = mysql_fetch_object($order_qry);
if( ! $order->ordered) { // If not ordered
// ... do something
} else { // If already ordered
// ... tell the client
}
} else {
// No record found ... error message here
}

Categories