I am trying to figure out how to use values in HTML (input value within a form) and use it in PHP. So far I have tried a variety of different solutions but I cannot seem to get it right. I want the values of 2 input fields, to be combined with a string value in the PHP section, how can I get the following to work?
Note: I am fairly new to PHP, so please elaborate on responses. :-) General: The contents is within a .php file ;
<form id="logForm" action="" method="GET">
<b class="logHeader" >Account Login</b>
<hr />
<input class="logInput" placeholder="Username" required="required" name="gguser">
<br />
<input class="logInput" type="password" placeholder="Password" required="required" name="ggpsw" >
<br />
<input class="buttonInput" type="submit" value="Login">
</form>
<?php
include("config.php");
if(isset($_GET['gguser']) && isset($_GET['ggpsw'])){
$conn = new mysqli($servername, $username, $password, $dbname);
echo $gguser $ggpsw;
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users WHERE username=" . $gguser . " AND userpsw=" . $ggpsw;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "APPLES";
} else {
echo "BANANAS";
}
$conn->close();
}
?>
CodePudding user response:
I see 2 main problems here :
First : $gguser and $ggpsw are not declared and can't work in your sql query anyway.
You're right checking if their GET equivalents exist with if(isset($_GET['gguser']) && isset($_GET['ggpsw'])){
but you have to crete new variables after if you want to use it, exemple :
if(isset($_GET['gguser']) && isset($_GET['ggpsw'])){
$conn = new mysqli($servername, $username, $password, $dbname);
$gguser = mysqli_real_escape_string($_GET['gguser']) ;
$ggpsw = mysqli_real_escape_string($_GET['ggpsw']) ;
Note that i've use mysqli_real_escape_string(), when you're using POST or GET data on sql query, never trust the data you receive, this function prevent sql injection !
The second main problem is a classic one, you're wrong with your sql query syntax, with quotes :
$sql = "SELECT * FROM users WHERE username=" . $gguser . " AND userpsw=" . $ggpsw;
Will never work as $gguser and $ggpsw are strings ! String condition in SQL have to be under quotes :
$sql = "SELECT * FROM users WHERE username='" . $gguser . "' AND userpsw='" . $ggpsw."' ";
I've add ' before and after each variables. This kind of syntax is a real pain for beginner, but there is it.
I would recommand you to add :
error_reporting(E_ALL);
ini_set("display_errors", "On");
On top of yours files, so you would have php errors displayed, debug is mandatory for a good progression. In you case, you would had explicits errors saying "$gguser is undefined".