This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
im working on a project for basically my friends and i to use. Maybe to use it for other games as well. SpeedRunning! i have made and was able to POST the Data into MySQL with THIS information
<?php include_once('include/action_page.php');?>
<!DOCTYPE HTML>
<meta charset="UTF-8">
<html>
<head>
<title>Roleplayer's Tavern Home</title>
<link href="/style/style.css" rel="stylesheet" type="text/css">
<script src="/include/jquery-1.11.2.min.js"></script>
<?php include_once('/include/rpt_site_no_script.php');?>
</head>
<body onload="">
<div class="page_container" name="page_container">
<div id="page_header">
<!-- The title of the webpage -->
<div style="max-width:250px; overflow:hidden">
<span id="header_title"><img src="style/logo.png" style="width:225px; height:67px;"/></span>
</div>
</div>
<!-- Left side bar -->
<div id="page_container_left">
<h3 id="page_content_header">Submit your data!</h3>
<?php include('include/submit_data.php');?>
</div>
<div id="page_container_right"
style="overflow-y: auto; max-height: 100%">
<h3 id="page_content_header">Donations for website?</h3>
<?php
?>
</div>
<!-- Main Content -->
<div id="page_content_container_main_page">
<div class="page_content_container">
<h2 id="page_content_container_header">Leaderboard WOO WOO</h2>
<hr>
<p id="page_content_container_content">
<h2>Players That Have Beaten Mad Pack 2</h2>
<?php include('include/leaderboard.php');?>
</div>
</div>
<br>
<!-- Footer -->
<div id="page_footer">
<ol id="footer_list">
<li>Copyright © Roleplayer's Tavern 2015-2016 - All Rights Reserved</li>
<li style="font-size:12px">Your IP address <?php echo $_SERVER['REMOTE_ADDR']; ?> will be logged for security reasons.</li>
</ol>
</div>
</div>
<script type="text/javascript">
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
window.onresize = function(event) {
var element=document.getElementsByName('page_container')[0];
var applyTo=document.getElementById('page_container_left');
var applyTo2=document.getElementById('page_container_right');
applyTo.style.height = (element.offsetHeight - 2) + "px";
applyTo2.style.height = (element.offsetHeight - 2) + "px";
}
</script>
</body>
</html>
as this is the HTML format.
Action_page.php is the page for submitting the information
<?php
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$sql = "INSERT INTO MineCraftRecords (MineCraftName, LevelSeed, Day, Time)
VALUES ('$_POST[MinecraftName]', '$_POST[LevelSeed]', '$_POST[Day]', '$_POST[Time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
$conn->close();
?>
<meta http-equiv="Location" content="https://rptavern.org/SpeedRun/">
and im having trouble on getting the page to LOAD the information provided into the leaderboard.php as this is what i have so far.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$servername = "localhost";
$username = "USERNAME";
$password = "PASSWORD";
$mysqlDatabaseName = "SpeedRun";
$query="SELECT * FROM MineCraftRecords";$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;while ($i < $num) {CODE$i++;}
$variable=mysql_result($result,$i,"fieldname");
$field1-name=mysql_result($result,$i,"MineCraftName");
$field2-name=mysql_result($result,$i,"LevelSeed");
$field3-name=mysql_result($result,$i,"Day");
$field4-name=mysql_result($result,$i,"Time");
$field5-name=mysql_result($result,$i,"id");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $mysqlDatabaseName);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Turtle Mode Activated";
?>
Im basically trying to base it off this website http://www.speedrun.com/mc but not as technical. Just to show the SpeedRunning time and have the TIME the top of the list.
Any help is awesome, as im very new to creating stuff like this. i will take the time to read everyone's comments and suggestions that you all can provide :D
I suggest cleaning up your code. Some thing that can be done is that you can separate the dB connect details into a separate file. This will optimize your code and will it make sure to change the details later on as your project grows.
If you would ever consider using PDO here is a code example that will help you out. I'm not sure if mySQLi is similar to PDO but have a look anyway. It's super easy to use and implement in as many pages as possible!
HTML/PHP (displaying data in table):
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
</head>
<body>
<?php
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
require_once("../DAL/db_functions.php");
//Run query on branch table
readQuery("M_Branch");
//If there are any details in branch table continue
if($numRecords === 0){
echo "<p>No Branches Found!</p>";
}
else{
$arrRows = NULL;
//Create table and headings
echo "<table id='mavis' border='1' width='100%'>";
echo "<tr>";
echo "<th>Branch Code</th>";
echo "<th>Branch Name</th>";
echo "<th>Manager</th>";
echo "<th>Branch Address</th>";
echo "<th>Suburb</th>";
echo "<th>State</th>";
echo "<th>Post Code</th>";
echo "<th>Phone Number</th>";
echo "<th>Fax Number</th>";
echo "<th></th>";
echo "</tr>";
while($arrRows = $stmt->fetch(PDO::FETCH_ASSOC)){
echo "<tr>";
echo "<td>".$arrRows['Branch_Code']."</td>";
echo "<td>".$arrRows['Branch_name']."</td>";
echo "<td>".$arrRows['Manager']."</td>";
echo "<td>".$arrRows['Branch_Address']."</td>";
echo "<td>".$arrRows['Suburb']."</td>";
echo "<td>".$arrRows['State']."</td>";
echo "<td>".$arrRows['Post_code']."</td>";
echo "<td>".$arrRows['Phone']."</td>";
echo "<td>".$arrRows['Fax']."</td>";
//Cannot delete already created records - Foreign key constraint fails
//If phpMyadmin were to delete one then other tables will incur problems
echo "<td><a href='edit_branch.php?ID=$arrRows[Branch_Code]'>Edit</a>";
echo "<br /><a href='../BLL/delete_confirm.php?TYPE=Branch&ID=$arrRows[Branch_Code]' onClick='return checkDelete()'>Delete</a></td></tr>";
}
echo "</table>";
echo "<form action='../DAL/add_branch.php' method='post'>";
echo "<input type='submit' value='Add a New Branch' />";
echo "</form>";
echo "<p></P><P>$numRecords Records Returned</P>";
}
?>
</body>
Here is my connect and readQuery function located in ../Db_functions.php
I have created functions that are reusable and can be used with multiple DB tables.
//Database connection Variables
$localhost = "localhost";
$user = "root";
$password = "root";
$db = "Mavis";
$dsn = "mysql:host=$localhost;dbname=$db";
//Declare Global Variables
$dbConnection = NULL;
$stmt = NULL;
$numRecords = NULL;
//This connect database function can be used to connect anywhere
function connect(){
//These are variables from the other file (dblibary) - global allows access to these variables
global $user, $password, $dsn, $dbConnection; //Required to access the global variables.
try{
$dbConnection = new PDO($dsn, $user, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $error){
//display error message if connection doesnt work
echo "The following error occured: " . $error->getMessage();
}
}
Read Query:
function readQuery($table){
global $numRecords, $dbConnection, $stmt;
connect();
$sqlStr = "SELECT * FROM " . $table.";";
try{
$stmt = $dbConnection->query($sqlStr);
if($stmt === false){
die("Error executing the qquery: $sqlStr");
}
}
catch(PDOException $error){
echo "An Error occured: " . $error->getMessage();
}
$numRecords = $stmt->rowCount();
//Close the DB connection
$dbConnection = NULL;
}
Related
So I'm working on a website where I need to pull data from a MySQL server and show it on a webpage. I wrote a simple PHP script to read data from the database depending upon an argument passed in the URL and it works just fine.
Here is the script:
<?php
function updator($item)
{
$servername = "localhost";
$username = "yaddvirus";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$table = "inventory";
//$item = "Rose Almonds";
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
//echo "0 results";
$conn->close();
}
if (defined('STDIN')) {
$item = $argv[1];
} else {
$item = $_GET['item'];
}
//$item = "Cherry";
updator($item);
?>
This script works exactly as expected. I call it using http://nutsnboltz.com/tester.php?item=itemname and it pulls and shows the data just fine.
P.S You can test it out by using Cherry or Blueberry as items.
The problem is, when I'm trying to put this data in my productpage.php file, I can't get the data to show up. Here's how the file hierarchy goes:
<php
*Exact same php script as above*
?>
<html>
<head>
Header and navbar come here
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-4">
<h1> RANDOM TEXT BEFORE </h1>
<?php
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
?>
</div>
<div class="col-8">
<H!> MORE RANDOM TEXT</h1>
</div>
</div>
</div>
</body>
<footer>
footer here
scripts etc
</footer>
</html>
So the script above the footer prints everything just fine. However, down where the HTML is, nothing is printed after the PHP code. It only shows my Navbar and the H1 tag saying "RANDOM TEXT BEFORE" and that's about it. My footer is gone along with everything else.
What exactly is the issue here and how do I fix this?
The problem seems to be that you're declaring $result inside the updator function, so it's not available when you're attempting to call it later.
The best thing to do might be to return $result from the function and assign that to a variable - something like this:
function updator($item)
{
// ... some code ...
$sql = "SELECT * FROM $table WHERE item = '$item'";
$result = $conn->query($sql);
// ... some more code ...
return $result;
}
<-- HTML CODE HERE -->
<?php
$item = !empty($_GET['item']) ? $_GET['item'] : false;
// yes I know it's a bit hacky to assign the variable
// within the 'if' condition...
if($item && $result = updator($item)) {
while($data=$result->fetch_assoc()){
echo "<h1>{$data['item']}</h1><br>";
echo "<h1>{$data['item_desc']}</h1><br>";
echo "<h1>{$data['price125']}</h1><br>";
echo "<h1>{$data['price250']}</h1><br>";
}
}
?>
I am trying to set the value to be displayed in a SELECT list using php scripts.
What I have done is create an input html page (MatchSelect.php) which shows two select boxes and a submit button.
On pressing the submit button a new new php file is called (MatchSelectResult.php) which is as follows;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Seniors Inter-Club Match Management</title>
<link rel="stylesheet" href="MainBody.css">
<link href="dropDown.css?v=1.1" rel="stylesheet" >
<?PHP require '../../configure.php';
include "Main_PHP_Code.php" ;
?>
</head>
<body>
<?PHP include "MatchPopulate.php"; ?>
<div class="container">
<?PHP include "menu.txt" ?>
<div class="content">
<div>
<h1>Team Selection</h1>
<form name="matchSelect" method="POST" action="MatchUpdate.php">
<p>
<select id = "Venue" name= "Venue" >
<option disabled selected value> -- select an option -- </option>
<option value="Away">Away</option>
<option value="Home">Home</option>
</select>
match against
<select id ="Opponents" name ="Opponents">
<?php
Global $OpponentName;
$oop = $OpponentName;
opponent_load('$oop');
?>
</select>
etc.
the function opponent_load() is contained within the "Main_PHP_Code.php" code and is as follows;
function opponent_load($oppon){
Global $OpponentName;
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM opponentsdb";
$result = mysqli_query($db_handle, $SQL);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['Opponents'];
if ($uName == $oppon)
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option value='$uName' $selected> $uName </option>";
}
}
else {
print "Database NOT Found ";
}
mysqli_close($db_handle);
}
The "MatchPopulate.php" code in the HEAD section is used to search the mySQL database using the two values from MatchSelect.php page. If the data is found, then the global variable $OpponentName is defined. The code is thus;
<?php
Global $OpponentName;
//require '../../configure.php';
$uOpponentName = $_POST['Opponents'];
$uVenue = $_POST['Venue'];
//$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementdb";
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// check to see if Match (Opponents + Venue)already in the database, if so, retrieve data or add match to database
$SQL = "SELECT * FROM teamselect WHERE Opponents = '$uOpponentName' AND Venue = '$uVenue'";
$result = $conn->query($SQL);
//if $result->num_rows >0 then retrieve data ELSE add match to database
if (!$result){
print "Error selecting record: " . $sql . "<br>" . $conn->error;
} else {
if ($result->num_rows >0) {
while($row = $result->fetch_assoc()) {
$OpponentName = $row['Opponents'];
}
} else {
$sql = "INSERT INTO teamselect (Opponents, Venue) VALUES ('$uOpponentName', '$uVenue')";
if ($conn->query($sql) === TRUE) {
} else {
print "Error adding record: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
The code stops when it tries to populate the Opponents Select box on MatchSelectResult.php. Any help to solve this would be appreciated.
I have solved the problem by opening a session and using $_SESSION["Opponents"] to pass the variable around the scripts.
Also changed opponent_load('$oop') to opponent_load($oop).
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I have been following this tutorial on CRUD in php but I have come across an error that I have failed to intercept
Fatal error. Call to member function prepare() on null in C:\xampp\htdocs\CRUD\read.php on line 29** and this error ion line 29 of my code is **$stmt = $conn->prepare($query);
read.php file is this
<!DOCTYPE html>
<html>
<head>
<title>PDO - Read Records - -PHP CRUD Tutorial</title>
<!--Bootstrap-->
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
</head> <body>
<div class="container">
<div class="page-header">
<h1>Read Products</h1>
</div>
<!--Dynamic content will go here-->
<?php
// include database connection
include_once 'config/database.php';
// select all data
$query = "SELECT id, name, description, price FROM products ORDER BY id DESC";
// prepare query for execution
$stmt = $conn->prepare($query);
// execute the query
$stmt->execute();
// this how to get number of rows returned
$num = $stmt->rowCount();
// link to create record form
echo "<a href='create.php' class='btn btn-primary m-b-1em'>Create New Product</a>";
// check if more than 0 records found
if($num > 0) {
echo "<table class='table table-hover table-responsive table-bordered'>"; // start table
// creating our table heading
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Name</th>";
echo "<th>Description</th>";
echo "<th>Price</th>";
echo "<th>Action</th>";
echo "</tr>";
// retrieve our table contents
//fetch() is faster than fetchAll()
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// extract row
// this will make $row['firstname'] to
// just $firstname only
extract($row);
// creating new tablerow per record
echo "<tr>";
echo "<td>{$id}</td>";
echo "<td>{$name}</td>";
echo "<td>{$description}</td>";
echo "<td>${$price}</td>";
echo "<td>";
// read one record
echo "<a href='read_one.php?id={$id}'class=''btn btn-info m-r-1em'>Read</a>";
// we will use this link to the next part of the post
echo "<a href='update.php?id={$id}' class='btn btn-primary m-r-1em'>Edit</a>";
// we will use this link to the next part of the post
echo "<a href='#' onClick='delete_user({$id});' class='btn btn-danger'>Delete</a>";
echo "</td>";
echo "</tr>";
}
//end table
echo "</table>";
}
// if no records found
else{
echo "<div class='alert alert-danger'>No records found.</div>";
}
?>
</div><!--end of container-->
<!--Jquery (necessary for bootstrap's javascript plugin)-->
<script src="jquery-ui-bootstrap-jquery-ui-bootstrap-71f2e47/js/jquery-1.8.3.min.js">
</script>
</body>
</html>
database.php file:
<?php
//variables used to connect to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "1phpbeginnercrudlevel1";
//create a connection using the PDO extension
try{
$conn = new PDO("mysql:host=$servername;dbname=1phpbeginnercrudlevel1",$username,$password);
//set the PDO error mode to exception
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " .$e->getMessage();
}
?>
Seems like your connection failed or including database.php was failed
An missing found in your database.php file:
you should must add "return $conn;" on try block
correction is given in below :-
<?php
//variables used to connect to the database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "1phpbeginnercrudlevel1";
//create a connection using the PDO extension
try{
$conn = new PDO("mysql:host=$servername;dbname=1phpbeginnercrudlevel1",$username,$password);
//set the PDO error mode to exception
return $conn;
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " .$e->getMessage();
}
?>
Hello, I've been stumped by the PHP code I've written. I've stared at this for hours with no success, please help find any errors I've apparently gone over.
What I want this script to do is from a html form page, to query a database table ('users') to make sure their password and username are correct, then in a separate table ('tokens') insert a random token (the method I used before, it works) into the 'tk' column, and the users general auth. code pulled from the 'users' table into the 'gauth' colum, in the 'tokens' table.
The reason for the additional general auth is so I can pull their username and display it on all the pages I plan on "securing"
Sorry if I'm confusing, this is the best I can refine it. Also, I'm not that good at formatting :). I'm going to add some html later, that's why the tags are there.
MySQL Tables:
Users Example:
cols: username | password | email | classcode | tcode | genralauth |
hello | world | hello.world#gmail.com | 374568536 | somthin | 8945784953 |
Tokens Example:
cols: gauth | tk |
3946893485 |wr8ugj5ne24utb|
PHP:
<html>
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "-------";
$password = "-------";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql1 = "SELECT username FROM users";
$data1 = $conn->query($sql1);
if ($conn->query($sql1) === TRUE) {
echo "";
}
?>
<?php
$sql2 = "SELECT password FROM 'users'";
$data2 = $conn->query($sql2);
if ($conn->query($sql2) === TRUE) {
echo "";
}
?>
<?php
$bytes = openssl_random_pseudo_bytes(3);
$hex = bin2hex($bytes);
?>
<?php
if($_POST['pss'] == $data2 and $_POST['uname'] == $data1) {
$correct = TRUE;
}
else {
$correct = FALSE;
}
?>
<?php
if ($correct === TRUE) {
$sql3 = "SELECT generalauth FROM users WHERE password='".$_POST['pss']."'";
$result3 = $conn->query($sql3);
}
?>
<?php
if ($correct === TRUE) {
$sql4 = "INSERT INTO tokens (tk,gauth) VALUES (".$hex."' , '".$result3."')";
if ($conn->query($sql4) === TRUE) {
echo "New token genrated.";
} else {
echo "Error: " . $conn->error;
}
}
?>
<?php
if ($correct === TRUE) { ?>
<p>Succesfuly loged in!</p><br/>
<button>Continue</button><br/>
<?php
}
elseif ($correct === FALSE) { ?>
<p>Incorrect, please try again.</p><br/>
<button>Back</button><br/>
<?php
}
?>
<?php
if ($correct === TRUE) {
$_SESSION['auth'] = $hex;
$_SESSION['logstat'] = TRUE;
}
?>
<?php
if ($correct === FALSE) {
$_SESSION['logstat'] = FALSE;
}
$conn->close();
?>
This is the PHP I'm going to use on most pages for token auth, howver it dosn't actually check the database 'tokens', also I need a way to display signed in users username using the general auth.
PHP:
<html>
<h1 class="title">Virtual Work Sheets!</h1>
<p class="h_option">[Log In / Register]</p><hr/>
<div class="body">
<?php
session_start();
error_reporting(0);
$servername = "localhost";
$username = "root20";
$password = "jjewett38";
$db = "vws";
?>
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<?php
$sql = "SELECT tk FROM tokens";
$data = $conn->query($sql);
?>
<?php
if (!$_GET['tk'] == $data) {
echo "
<p>Invalid token, please consider re-logging.</p>
";
}
else {
?>
<?php
switch ($_GET['view']) {
case teacher:
?>
Teacher page html here...
<?php
break;
case student:
?>
Student page html here...
<?php
break;
default:
echo "Please login to view this page.";
}
}?>
</html>
I suggest that you change your approach.
Although at first glance these example files looks like a lot, once you study them you'll see it's really much more simple and logical approach than the direction you are now headed.
First, move the db connect / login stuff into a separate file, and require or include that file at top of each PHP page:
INIT.PHP
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Might as well also load your functions page here, so they are always available
require_once('fn/functions.php');
?>
Now, see how we use it on the Index (and Restricted) pages?
INDEX.PHP
<?php
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<!-- Examples need jQuery, so load that... -->
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<!-- and our own file we will create next... -->
<script type="text/javascript" src="js/index.js"></script>
<div id="pageWrap">
<div id="loginDIV">
LoginID: <input type="text" id="liID" /><br>
LoginPW: <input type="password" id="liPW" /><br>
<input type="button" id="myButt" value="Login" />
</div>
</div>
JS/INDEX.JS
$(function(){
$('#myButt').click(function(){
var id = $('#liID').val();
var pw = $('#liPW').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +id+ '&pw=' +pw,
success: function(d){
if (d.length) alert(d);
if (d==1) {
window.location.href = 'restricted_page.php';
}else{
$('#liID').val('');
$('#liPW').val('');
alert('Please try logging in again');
}
}
});
});//END myButt.click
}); //END document.ready
AJAX/LOGIN.PHP
<?php
$id = $_POST['id'];
$pw = $_POST['pw'];
//Verify from database that ID and PW are okay
//Note that you also should sanitize the data received from user
if ( id and password authenticate ){
//Use database lookups ot get this data: $un = `username`
//Use PHP sessions to set global variable values
$_SESSION['username'] = $un;
echo 1;
}else{
echo 'FAIL';
}
RESTRICTED_PAGE.PHP
<?php
if (!isset($_SESSION['username']) ){
header('Location: ' .'index.php');
}
require_once('inc/head.inc.php');
require_once('fn/init.php');
?>
<body>
<h1>Welcome to the Admin Page, <?php echo $_SESSION['username']; ?>
<!-- AND here go all teh restricted things you need a login to do. -->
More about AJAX - study the simple examples
I can't seem to find a way to block my page from being accessed. I have a page to give tickets to users in mysql, but you can simply type it into http to receive tickets, how do i stop people from doing that??
<html>
<head>
<?php
header("refresh:33;url=tickets_give.php" );
?>
<link rel="stylesheet" href="finessecss.css">
</head>
<body bgcolor="#F9F9F9" background="background3.jpg">
<div class="videobox">
<div class="video"><p>Video Player Unavailable At This Moment</p></div>
<div class="clockbox">
<span id="countdown" class="timer"></span>
<script>
var seconds = 30;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown')[0].innerHTML = "";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
</div>
</div>
</body>
</html>
There is my code for my video page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users_database";
session_start();
$name = $_SESSION['name'];
$pass = $_SESSION['pass'];
if (!(isset($_SESSION['can_accesss']) && $_SESSION['name'] != '')) {
Header("Location:welcome_get.php");
}
unset($_SESSION['can_access']);
// rest of page code
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ('$access' == 'Finesseshopisthebest'){
;
}
else{
echo'mysql' or die;
}
$sql = "UPDATE users_database SET tickets=tickets+10 WHERE username= '$name' and password= '$pass'";
if (mysqli_query($conn, $sql)) {
Header("Location:tickets.php");
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
</body>
</html>
And that is my give tickets page. How do i stop people from going straight to tickets_give.php?
If you're looking for a 20-second solution, just check for the presence of a precise query string, eg yoursite.com/somepage?foo=bar. If $_GET["foo"] is not set, call exit and forget about it.
Warning: this is security through obscurity; anyone with a network monitor or even just shoulder surfing would breeze past this, but I guess it's better than nothing. Clearly a smarter, long-term solution is to add meaningful authentication, but it sounds like you have a very short-term problem you need to solve!