Firstly, Sorry for bad English :(
I want key system like steam, origin or uplay. I give keys to user, user write that code into input, and code will echo user's code.
I have 1 Table. 2 Columns in it. 2 Rows for 2 Column. Like this:
.----------------------.
| sifre | bizimkey |
|______________________|
| A5Sr2A | First Code |
|______________________|
| FaQ1fS | Scnd. Code |
|______________________|
If user enters A5Sr2A into Input, PHP Echos "First Code". If user enters wrong code, Just appear alert.
I tried so many codes. I can run the code like this:
<?php
if ($_POST['pass'] == "A5Sr2A") {
{
echo "First Code";
}
} else {
header('Location:index.html');
}
?>
But I don't want this. This is so challenging thing. I asked myself, "Why don't you use MySQL?"
I am trying 7 Hours. Really. I want to do that. I want learn MySQL. Please Help. THANKS!
<? ob_start(); ?>
<html>
<link rel=stylesheet href="style.css">
<table>
<tr>
<td>
<center>
<?php
$host = "localhost";
$user = "user";
$password = "pass";
$database = "db";
$con = mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
echo "ERROR";
}
$result = m ysqli_query($con, "SELECT sifre FROM keyler");
if ($_POST['pass'] == $ result) {
{
$mykey = m ysqli_query($con, "SELECT bizimkey FROM keyler");
echo $mykey;
}
} else {
header('Location:index.html');
}
mysqli_close($con);
?>
</center>
</td>
</tr>
</table>
</html>
<? ob_flush(); ?>
Okay, see below for a basic implementation example:
$host = "localhost";
$user = "user";
$password = "pass";
$database = "db";
$con=mysqli_connect($host,$user,$password,$database);
if(mysqli_connect_errno()!=0)//mysqli_connect_errno() returns 0 when there are no errors
{
echo "ERROR";
}
$sifre_test = mysqli_real_escape_string($con,$_POST['pass']);
$result = mysqli_query($con,"SELECT '1' FROM `keyler` WHERE `sifre`='".$sifre_test."'");
if($result!==false)
{
//If $result !== false, the query was successful, so we'll try to grab a row
$row = mysqli_fetch_assoc($result);
//$row will be null if there wasn't a row found where `sifre`=$sifre_test
if(!is_null($row))
{
$result = mysqli_query($con,"SELECT `bizimkey` FROM `keyler` WHERE `sifre`='".$sifre_test."'");
if($result!==false)
{
$row = mysqli_fetch_assoc($result);
$bizimkey = $row['bizimkey'];
echo $bizimkey;
}
else
{
die("bizimkey query failed");
}
}
}
else
{
die("sifre query failed");
}
For a better understanding and more examples, see the documentation links below:
mysqli_query
mysqli_fetch_assoc
Related
I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string
This question already has an answer here:
Why does mysqli num_rows always return 0?
(1 answer)
Closed 6 years ago.
I want to make instant search (google like) on key up Jquery ajax must ass value from HTML input field to PHP and PHP must chec in SQL table named "title" for any words which Begin or Contain the written word/letter,if there isn't anything found it must print the results out in a div.
Here is an example:
The picture explains: Up is the input field and down box is the box for results to be printed,as we can see it is working,but PHP don't want to get data from SQL,and only printing the result for 0 value (Nothing Found) on Bulgarian language.
There is my code:
<?php
$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch = "";
if (!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$req->bind_param('s', $fsearch);
$req->execute();
if ($req->num_rows == 0) {
echo 'Не бяха намерени резултати!';
}
else {
while ($row = $req->fetch_array()) {
?>
<div class = "search-result">
<span class = "result-title">
<? php
echo $row['title'];
?>
</span><br>
</div>
<?php
}
}
}
?>
The code is working till else {...} only this part didn't work..;/
I tried to use echo some results after else {...} because i thought it was a problem with my code,but it didn't work either way ...Can somebody explain to me where is my mistake (with simple language please) i am not really good at coding exept with PHP.
I won't put Jquery and HTML here because all working fine there, the post method is all good, the problem is with the php. But of course if you need it to help me I will paste it with no problem.
Edited
$value = '%'.$fsearch.'%;
$req->bind_param('s', $value);
it will work :)
<?php
$hostname = "localhost";
$username = "username";
$password = "pass";
$databaseName = "dbName";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch="";
if(!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$value = '%'.$fsearch.'%';
$req->bind_param("s", $value);
$req->execute();
$req->store_result();
if ($req->num_rows == 0){
echo 'Няма резултати';
}
else{
echo 'ДАА';
}
}
FINALY !!! that is the final result,it is printing ДАА when there is a result found and Няма резултати when there isn't any results fixed it after 1 month of pain lol Thanks to everyone which helped me <3<3 <3 <3 <3
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!
I am trying to check if the session username matches the record in my database and if it does, I want to include a file.
This is my code
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT * FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez)
{
include('check.php');
}
else
{
echo "error";
}
?>
The session username does not match the record in my database, yet the file is being included. Why?
OH, I FOUND THE ISSUE. IT IS CONSIDERING MY USERNAME TO BE ROOT...BUT WHEN I SAY ECHO $_SESSION['USERNAME'] IT IS CRAIG#CRAIG.COM..WHY SO>
<?php
$username = $_SESSION['username'];
echo $username;
include('connect.php');
mysqli_select_db($connect,"persons");
$sql = "SELECT sessionusername FROM users WHERE sessionusername='$username'";
$r = mysqli_query($connect,$sql) or die(mysqli_error($connect));
$geez = mysqli_fetch_array($r);
if($geez["sessionusername"]==$username)
{
include('check.php');
}
else
{
echo "error";
}
?>
You are simply testing whether the array $geez is empty or not. If the array has anything in it, you if($geez) will return true. To stop this behaviour, please see ceteras' answer, particularly this part:
if($geez["sessionusername"]==$username)
{
include('check.php');
}
I believe that's the only part that has changed.
Thanks,
James