The following code works well when the correct URL is used like...
http://example.com/user.php?id=joe
Where I need help is where do I add an if statement and how should it be written to provide either a default landing page or better, an input field so the visitor can retype the user name and submit it to have the correct page load.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=users', 'root', '');
// retrieve member's data
$ps = $pdo->prepare("SELECT * FROM members WHERE id = ?");
if(isset($_GET["id"])) {
$ps->execute(array($_GET["id"]));
}
$result = $ps->fetch(PDO::FETCH_ASSOC);
extract($result);
echo $First_Name . ' - ' . $Email;
Any help?
if(!empty($_GET['id'])) {
// YOUR PREVIOUS CODE HERE
} else {
// REDIRECT CODE HERE
}
I assume you'd want to wrap all the code with the if statement so it doesn't run unless an id is present.
<?php
if( isset( $_GET['id'] ) ) {
//retrieve member data here and render normal page
}
else {
//render landing page
}
?>
It might be wise to put the code for rendering the two different pages into different functions to help with organization as well.
Related
I'm creating a profile page where the name of the user can be edited. I can't seem to figure out how to update the name of the user that is displayed at the top page (i.e. Hi Kana!) after a successful edit.
The name is generated using a session variable at the top of my page, $_SESSION['username']
<?php
session_start();
if(isset($_POST['submit']) && isset($_SESSION['newusername'])){
unset($_SESSION['username']); //clear existing username session
$_SESSION['username'] = $_SESSION['newusername']; //replace with the new username
echo $_SESSION['username'];
} else {
echo $_SESSION['username'];
}
?>
After hitting the submit button with a different name set on the text input it should change but it does not. These are the lines of codes after the code I mentioned above.
<?php
$textinput = $_POST['textinput'];
if(isset($_POST['submit']))
{
if(strlen($_POST['textinput']) < 2)) {
$errormessage = 'too short';
}
else
{
$_SESSION['newusername'] = $textinput; //setup a new session for the new username to be used above.
}
}
?>
Note that the two quoted set of codes are in the same page.
What happens is that the name still shows the previous name, which is supposedly overwritten. I tried refreshing the page but it still does not change, I need to submit again (2nd time) to show the new name.
You can and should drastically simplify your code. Currently there are a variety of unnecessary operations here. Consider semantically what you want to accomplish:
If the user submits their name, update the session with the new value. Then output the value.
That's it. Let the semantics of what you want to accomplish guide how you accomplish it. Start the session, check for the form post, conditionally update the value, output the current state of the value. For example:
<?php
session_start();
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
Maybe you'll want to add a sensible default in the absence of a username. That would just be something like:
<?php
session_start();
// set a default value
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "Default User";
}
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
When you log in by my login form authentication.php will check if the data from the inputs excists in the database. When there is a match the user will be directed to a page for his role so lets say the user is a admin he will be directed to admin.php. When the user is successfully logged in i want to show a message like welcome firstname lastname. In my database i have a field called firstname and a field called lastname. I hope someone can help me with this since i cannot seem to figure it out :(
authentication.php
<?php
session_start();
// Making a connection with the database.
$mysqli=new MySQLi("localhost", "root", "root", "portfolio");
$role="";
// Declaring the username and password input.
$username=filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password=filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// If role from members where username and password from inputs exicts in database bind parameters.
// If given parameters not excists in database die
if($query=$mysqli->prepare("SELECT `role` FROM members WHERE username=? AND password=?")) {
$query->bind_param("ss", $username, $password);
$query->execute();
$query->bind_result($role);
$query->fetch();
} else {
echo "Errors in the Query. ".$mysqli->error;
die();
}
// If $role is filled make session for username to check if logged in and session role for redirect page.
// If $role and $username is not filled invalid password, username combination.
if($role!="") {
$_SESSION['ingelogt']=$username;
$_SESSION['user_role']=$role;
$location="$role.php";
header("location: $location");
} else {
echo "Invalid password, username combination";
echo "<br/><a href='login.html'>Click to go back</a>";
}
?>
The page the admin will be directed to called admin.php
<?php
session_start();
// If session is not ingelogt lead back to index.php.
if(!isset($_SESSION['ingelogt'])) {
header("location: index.php");
}
// The role that has access to this page.
$page_role="admin";
$role=$_SESSION['user_role'];
// If a user with a different role visits wrong page.
if($role!=$page_role)
{
echo "You are not supposed to be here.";
die();
}
// Start new DOMDocument and load html file.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile("admin.html");
libxml_use_internal_errors(false);
// If user is logged in add logg out icon in the menu.
if($_SESSION['ingelogt']) {
$oUl = $dom->getElementById('navUl');
$oList = $dom->createElement('li');
$oLink = $dom->createElement('a');
$oLink->setAttribute('href','logout.php');
$oI = $dom->createElement('i');
$oI->setAttribute('class','icon-logout');
$oLink->appendChild($oI);
$oList->appendChild($oLink);
$oUl->appendChild($oList);
}
// Save DOMDocument with html document.
echo $dom->saveHTML();
?>
If I'm misunderstanding you in any way, just give me a hint, and I will delete this answer. Although what I assume that you want to do is to print the greeting somewhere on the page, based off the user's first name and surname.
Basically, once you have declared a $_SESSION-element, you can access it at different pages (similar to $_COOKIE, but not identical). So the best solution for this is to initialize $_SESSION variables with the first- and last name you receive from the database, and then print those variables on the desired pages (same method as you've used with the role).
Firstly, you need to fetch the names in the database, which can be done by changing the if-statement in authentication.php to the following:
if($query=$mysqli->prepare("SELECT `role`, `firstname`, `lastname` FROM members WHERE username=? AND password=?")) //assuming that your columns are called `firstname` and `lastname`
To fetch these, you also need to change the row further down to:
$query->bind_result($role, $first, $last);
When using fetch on the next row, your variables will be put into their appropriate bound ones. So after that statement, you can do the following (preferably after the $_SESSION['user_role']=$role;):
$_SESSION["firstname"] = $first;
$_SESSION["lastname"] = $last;
After that point, you can echo the first- and last name wherever you want (it depends on where you want it to be put...). If you want it to appear at the top of admin.php, for instance, you can simply put this before $dom = new DOMDocument();:
echo "Hello " . $_SESSION["firstname"] . " " . $_SESSION["lastname"] . "!";
If you're confused where to put something, then try re-reading the given instructions. Most of my examples are simply things to replace (in which case, you just need to find the corresponding code), and if not that, I've tried to redirect you. Although realize that things like these are important to know without getting the code right in your hand, so I advice you to try to understand.
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
Basically what i am trying to do here is to read from the table in my database using the customers login details, then retrieve the record that matches this information. In this table there is a column called "AccountType", this differentiates the average user from a manager, if this column is 1, they are a average user. If this column is 2, they are a manager.
Now im having issues implementing this in my code, below is the snippet of my process script for the login:
<?php
***session_start()
$query = mysql_query("SELECT * FROM accounts WHERE username='$username' and password='$password'", $db) or die ("Query failed with error: ".mysql_error());
$count=#mysql_num_rows($query);
if(***$count == 1)
{
***$user_row = mysql_fetch_array($result)
$userid = $user_row["userid"];
$_SESSION['userid'] = $userid;
$customername = $user_row["customername"];
$_SESSION['customername'] = $customername;
$AccountType = $user_row["accounttype"];
if ($AccountType == 2)
{
$_SESSION['manager'] = $AccountType;
}
Depending on this, when my check login script which every page includes, it will display specific links on the navigation depending what there account type is, if they are user they will have access to normal links, but if they are a manager they have access to admin functions, below is the code snippet for this also:
***session_start();
if (***isset($_SESSION['userid']))
{
$employeeid = $_SESSION['userid'];
$firstname = $_SESSION['customername'];
if (***isset($_SESSION['manager']))
{
$User_Options .='Manager links go here';
}
else
{
$Links .='Normal Links go here';
}
}
Thats just a basic truncated version, but that gives the basis of what im trying to accomplish. I am guessing down to using the while loop its overwriting the session, which i understand, however there will only be one record for the information i am searching. It works to some extent, however even if the AccountType is 1, it displays the options for 2.
Can anyone assist me further in solving this issue? Thankyou!
Use something like this on the login form:
$_SESSION['manager'] = false;
if ($AccountType == 2) {
$_SESSION['manager'] = true;
}
then later:
if ($_SESSION['manager']) {
// display manager-only options
} else {
// display user-only options
}
// Display options for everyone here
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.