I have a value that I receive from another url from $_SESSION. It arrives glued together with a second value I needs as {$is:$user} or {2:bob}. I split them with they with explode and 'attempt' to assign them as $_SESSION['id'] = $pieces[0]; and $_SESSION['cust_name'] = $pieces[1];
The first time the process works prefect. the values are segmented and they go to the proper place.
But following my selected submit, I lose the value of $_SESSION['cust_name']
How can I retain the value of $_SESSION['cust_name'] following my selection?
<?php
session_start();
if(isset($_POST['SubmitForRedirect'])){
//store as session variable
$_SESSION['printdata'] = $_POST['bolredir'];
//forward browser
die(header("Location: add-job.php"));
}
require_once("header2.php");
//var_dump($_SESSION['id']);
//var_dump($_SESSION['cust_name']);
$cust_info = $_SESSION['id'];
$pieces = explode(":", $cust_info);
//if(isset($_SESSION['cust_name']))
$_SESSION['id'] = $pieces[0];
$_SESSION['cust_name'] = $pieces[1];
//else
//echo "Something died";
echo $pieces[0];
?><br /><?php
echo $pieces[1];
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- <link href="style.css" rel="stylesheet" type="text/css" /> -->
<title> Contacts Database </title>
</head>
<body>
<h2> Select and existing job for: <?php echo $_SESSION['cust_name']; ?> with the ID of: <?php echo $_SESSION['id']; ?> and select print options</h2>
<?php
// selection box submit
try{
$conn = new PDO("mysql:host=localhost;dbname=$db", $user, $pass);
$stmt = $conn->prepare("SELECT * FROM customer INNER JOIN orders ON orders.cust_id = customer.id WHERE id =".$_SESSION['id']);
$stmt->execute();
$result = $stmt->fetchAll();
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="bolredir">
<option></option>
<?php
foreach ($result as $item){
echo '<option value='.$item['cust_id'].'>';
echo ($item['ship_name'] .",". $item['ship_addr'] .",". $item['total_price'].",". $item['cust_id']."<br />\n");
echo '</option>';
}
}
catch (PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
?>
</select>
<input type="submit" name="SubmitForRedirect" value="Submit" />
</form>
</body>
You must put session_start() at the top of every page before any output if you wish to use sessions:
<?php
session_start();
require_once("header2.php");
It looks like you are overwriting $_SESSION['id'] on every request.
You would normally set this only once, upon signon.
Related
I have created a customer database in which 4-5 staff will have access to login to view, edit and delete records.
I need the html table that lists the customer records to show an 'Edit' and 'Delete' link only when the logged in userID ($_SESSION[userID]) matches the userID of who created the record. So, if a staff member created 3 out 5 records, they should only see an 'edit' and 'delete' hyperlink against these three records, and nothing on the other two.
I have managed to get to the point of the sessions working - however, being new to PHP I am not sure where exactly to put my IF statement to echo the 'Edit' and 'Delete' links - and completely lost in how to write it exactly. I have tried many attempts, but am tearing my hair out now! Any help will be hugely appreciated.
This is my session start file (authenticate.php):
<?php
session_start();
$_SESSION["staffID"] = "staffID";
?>
Staff login file (staff_login.php):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff login</title>
</head>
<body>
<?php
require("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM `staff login` WHERE username='$username'
and password='$password'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION[staffID] = $rows["$staffID"];
// Redirect user to edit_contact.php - was index.php -
header("Location: edit_contact.php");
}
else
{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='staff_login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Staff login</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
And the php file to show the records in a table with the 'Edit' and 'Delete' hyperlinks:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit contact</title>
</head>
<body>
<h2>Tate Finance Customer contact details</h2>
<?php
//***edit_contact.php***///
// Developed by: []
// Contact: []
// Created: [November 2018]
// Last Modified: [26 November 2018]
/* Purpose: This file lists all contacts from the mycontacts database in a table for logged in users to add, edit or delete their contacts.*/
//include authenticate.php file on all secure pages
require('db.php');
include("authenticate.php");
?>
<!--Add welcome note to staff user-->
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>Logout</p>
<h3>Add new customer</h3>
<?php
$con = mysqli_connect("localhost","root","xxxxxx","mycontacts");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// Show all contacts from database in a table list
$query = "SELECT * FROM contact ORDER BY conName ASC";
$rst = mysqli_query($con,$query);
if($rst)
{
if(mysqli_num_rows($rst)>0)
{
// Table design for contacts list
echo "<table border='1'><tr><td>Edit contact</td><td>Name</td><td>Address</td><td>Phone</td><td>Mobile</td><td>Email</td></tr>";
while ($row = mysqli_fetch_assoc($rst))
{
/* Present contacts details in table list according to id selected, with links to edit or delete according to contactID selected */
/* This is where I think my IF statement needs to go, but can't figure out how/what to write to make it work */
echo "<tr><td>Edit Delete</td><td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
echo "</table>";
}
}
else
{
echo "No results found";
}
}
?>
</body>
</html>
while ($row = mysqli_fetch_assoc($rst))
{
echo "<tr>";
if($_SESSION["staffID"] == $id_of_creator){
echo "<td>".
"Edit".
"<a href=delete_record.php?
id=".$row['contactID']."> Delete</a> ".
"</td>";
}else echo "<td></td>";
echo "<td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
<?php
while($row = mysqli_fetch_assoc($selectAllCustomer)){
$id = $row['customer_id'];
$name= $row['customer_id'];
$email= $row['customer_email'];
echo "<tr>";
if($_SESSION['staffID'] == $Admin_Id){
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
echo "<td>";
echo "<a href='editPage.php?edit='".$id."'>Edit</a>";
echo "</td><td>";
echo "<a href='deletePage.php?delete='".$id."'>Delete</a>";
echo "</td>";
}else{
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
}
echo "</tr>";
}
NB: the valiable $admin_Id, is a id of the creator
?>
I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
I'm creating a website with a login.
Here is my login.php:
<?php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
$username="";
$finished = false;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo '<p class="error">login failed';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul></p>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo '<p class="error">Something went wrong while registering. Please try again later.</p>';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
if(mysql_num_rows($result) == 0)
{
echo '<p class="error">You have supplied a wrong user/password combination. Please try again.</p>';
}
else
{
$_SESSION['signed_in'] = true;
while($row = mysql_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
echo 'Successfully logged in as ' . $_SESSION['user_name'];
$finished=true;
}
}
}
}
if(!$finished) {
echo '<form method="post" action="">
<table>
<tr>
<td>Username:</td><td> <input type="text" name="user_name" value="' . $username . '"/></td>
</tr>
<tr>
<td>Password:</td><td> <input type="password" name="user_pass"/></td>
</tr>
</table>
<input type="submit" value="login" />
</form>';
}
include 'footer.php';
?>
my header.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="description" content="A short description." />
<meta name="keywords" content="put, keywords, here" />
<title>PHP-MySQL forum</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<h1>My forum</h1>
<div id="wrapper">
<div id="menu">
<a class="item" href="index.php">Home</a> -
<a class="item" href="/forum/create_topic.php">Create a topic</a> -
<a class="item" href="/forum/create_cat.php">Create a category</a>
<div id="userbar">
<?php
if($_SESSION['signed_in'])
{
echo 'Hello' . $_SESSION['user_name'] . '. Not you? Sign out';
}
else
{
echo 'Log in or create an account.';
}
?>
</div>
</div>
<div id="content">
and the footer:
</div><!-- content -->
</div><!-- wrapper -->
</body>
</html>
Now when i login succesfully, and i try to access the $_SESSION['signed_in'] in the header it is not set(i tried an output with echo and it didnt show anything). 'user_name' etc. is also not set, but in the login.php it has the correct content. What am i doing wrong?
For sessions to work in PHP, you must start them first using session_start(). You can do that in your script by either adding that at top of login.php or connect.php, Like below:
<?php
session_start();
include 'connect.php';
Better add it in connect.php to make it available on all other pages as well.
WARNING
mysql_* is DEPRECATED as of php-5.5 and was REMOVED in php-7.0. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?
on the first line, the first thing to do is to create the session.
<?php
session_start();
?>
remember to write this line as the first thing on every file which uses the session variables
so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>
Can anyone help me to extract the following php codes into a separate file? Below is the code:
<?php
//ini_set('display_errors', true);//Set this display to display all erros while testing and developing the script
//////////////////////////////
require "config.php"; // Database Connection
echo "<!doctype html public \"-//w3c//dtd html 3.2//en\">
<html>
<head>
<title>Demo script from example.com</title>
</head>
<body>
";
echo "<input id=\"city\" list=\"city1\" >
<datalist id=\"city1\" >";
//// Collect options from table ///
$sql="select city from city "; // Query to collect records
foreach ($dbo->query($sql) as $row) {
echo "<option value=\"$row[city]\"/>"; // Format for adding options
}
//// End of data collection from table ///
echo "</datalist>";
?>
<center>
<br><br>a href='http://www.example.com' rel='nofollow'>example.com : Footer text.</a></center>
</body>
</html>
Below is the database connection file, just for reference:
<?php
///////// Database Details , add here ////
$dbhost_name = "localhost";
$database = "test"; // Your database name
$username = "root"; // Login user id
$password = "test"; // Login password
/////////// End of Database Details //////
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
I just want to extract the PHP code in the main display page for a cleaner code structure.
Usually, the way to do this is to put your HTML in a "template" and your PHP code in another file. You can use a full-featured template engine like Smarty or Plates, or you can just place your HTML in a separate PHP file. Let's say your main file is called myfile.php. Make a new file called myfile.template.php.
In myfile.php:
<?php
require "config.php";
$cities = array();
$sql = "SELECT city FROM city";
foreach ($dbo->query($sql) as $row)
{
$cities[] = $row['city'];
}
include('myfile.template.php');
In myfile.template.php:
<!DOCTYPE html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>Demo script from example.com</title>
</head>
<body>
<input id="city" list="city1" />
<datalist id="city1" >
<?php foreach ($cities as $city): ?>
<option value="<?php echo $city; ?>" />
<?php endforeach; ?>
</datalist>
<div align="center">
<br><br>
<a href='http://www.example.com' rel='nofollow'>example.com : Footer text.</a>
</div>
</body>
</html>