Query is TRUE when its not - php

Please be gentle with me i have just recently trying to learn PHP/SQL.
The problem is that the first query is ALWAYS TRUE when it shouldn't (base on what i know).
The query simply state to get the 'username' where betakey=$betakey provided by user. The fact that my datebase columns is still empty except column betakey doesn't make that query statement true at all.
Please help, maybe i am missing some knowledge on this.
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host="localhost"; // Host name
$db_username="**"; // Mysql username
$db_password="**"; // Mysql password
$db_name="**"; // Database name
$conn = mysqli_connect("$host", "$db_username", "$db_password","$db_name");
if (!$conn){
die ("Error: ".mysqli_connect_error());
}
$query1 = "SELECT username='$username' FROM users2 WHERE betakey='$betakey';";
$result_1 = mysqli_query($conn,$query1);
if(mysqli_num_rows($result_1) > 0){
echo 'Beta key is used';
}else{
$query2 = "UPDATE users2 SET firstName='$firstName',lastName='$lastName',username='$username',password='$password' WHERE betakey='$betakey'";
echo 'Registration Successful';
}
mysqli_close($conn);//Close off the MySQL connection to save resources.
?>

You have plenty of problems in your code. Let me help you fix some of them
You should learn how to properly open mysqli connection. You need to enable error reporting and set the correct charset.
You should never concatenate PHP variables into SQL query. Always use parameterized prepared statements instead of manually building your queries.
Your first SQL query has an error. username='$username' is meaningless and wrong. If all you want to do is check existence use COUNT(1) or something similar.
Here is my take on your fixed code:
<?php
header('Access-Control-Allow-Origin: *');
$firstName = $_GET['rfirstname'];
$lastName = $_GET['rlastname'];
$username = $_GET['rusername'];
$password = $_GET['rpass'];
$betakey = $_GET['rkey'];
$host = "localhost"; // Host name
$db_username = "**"; // Mysql username
$db_password = "**"; // Mysql password
$db_name = "**"; // Database name
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($host, $db_username, $db_password, $db_name);
$conn->set_charset('utf8mb4');
$stmt = $conn->prepare("SELECT COUNT(username) FROM users2 WHERE betakey=?");
$stmt->bind_param('s', $_GET['rusername']);
$stmt->execute();
$result_1 = $stmt->get_result();
$used = $result_1->fetch_row()[0];
if ($used) {
echo 'Beta key is used';
} else {
$stmt = $conn->prepare("UPDATE users2 SET firstName=?, lastName=?, username=?, password=? WHERE betakey=?");
$stmt->bind_param('sssss', $firstName, $lastName, $username, $password, $betakey);
$stmt->execute();
echo 'Registration Successful';
}

Related

How do I get the value of the form into a MySQL table? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
All I want is to get the var1 from the input into my SQL table. It always creates a new ID, so this is working, but it leaves an empty field in row Email. I never worked with SQL before and couldn't find something similar here. I thought the problem could also be in the settings of the table, but couldn't find anything wrong there.
<input name="var1" id="contact-email2" class="contact-input abo-email" type="text" placeholder="Email *" required="required"/>
<form class="newsletter-form" action="newsletter.php" method="POST">
<button class="contact-submit" id="abo-button" type="submit" value="Abonnieren">Absenden
</button>
</form>
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
// Connection to DBase
$con = new mysqli($host, $user, $password, $dbase) or die("Can't connect");
$var1 = $_POST['var1'];
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
$result = mysqli_query($con, $sql) or die("Not working");
echo 'You are in!' . '<br>';
mysqli_close($con);
is the id a unique id? that's auto-incremented??
if so you should do something like this
<?php
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host,$user,$password,$dbase);
$email = $_POST['var1'];
// you might want to make sure the string is safe this is escaping any special characters
$statment = $mysqli->prepare("INSERT INTO table (Email) VALUES (?)");
$statment->bind_param("s", $email);
if(isset($_POST['var1'])) {
$statment->execute();
}
$mysqli->close();
$statment->close();
Simple answer
There are a few things wrong here; but the simple answer is that:
$sql = "INSERT INTO table (id, Email) VALUES ('?', '_POST[var1]')";
...should be:
$sql = "INSERT INTO {$table} (id, Email) VALUES ('?', '{$var1}')";
...OR assuming id is set to auto-increment etc. etc.
$sql = "INSERT INTO {$table} (Email) VALUES ('{$var1}')";
More involved answer
You should really take the time to use prepared statements with SQL that has user inputs. At the very least you should escape the strings yourself before using them in a query.
mysqli
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
$mysqli = new mysqli($host, $user, $password, $dbase); // Make connection to DB
if($mysqli->connect_error) {
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("s", $email); // Bind $email {s = data type string} to the ? in the SQL
$query->execute(); // Execute the query
PDO
$user = "user";
$password = "password";
$host = "localhost:0000";
$dbase = "base";
$table = "table";
try {
$pdo = new pdo( "mysql:host={$host};dbname={$dbase}", $user, $password); // Make connection to DB
}
catch(PDOexception $e){
die("Error: Could not connect to database.");
}
$email = $_POST["var1"]; // User input from form
$sql = "INSERT INTO {$table} (Email) VALUES(?)"; // SQL query using ? as a place holder for our value
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$email]); // Execute the query binding `(array)0=>$email` to place holder in SQL

PDO Username validation if already exists

I have a problem with register form.My form works properly but whenever i try to insert username that already exists it doesn't shows any error.
here is my php register file:
<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=dblogin", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
else{
$insert = $conn->prepare("INSERT INTO users (user_name,user_email,user_pass) values(:user_name,:user_email,:user_pass)");
$insert->bindparam(':user_name',$user_name);
$insert->bindparam(':user_email',$user_email);
$insert->bindparam(':user_pass',$hash);
$insert->execute();
}
}
catch(PDOException $e)
{
echo "connection failed";
}
?>
Thanks for your support
You are not executing the select statement. You need to bind params and execute the select statement, try this after the select statemnt.
$stmt->bindparam(':user_name',$user_name);
$stmt->execute();
public function usernameCheck($username)
{
$sql = "SELECT * FROM $this->table where username = :username";
$query = $this->pdo->prepare($sql);
$query->bindValue(':username', $username);
$query->execute();
if ($query->rowCount() > 0) {
return true;
} else {
return false;
}
}
use this one in your project hope it will work... :)
missing } in if statement
if (isset($_POST['submit'])) {
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_pass = $_POST['user_pass'];
$hash = password_hash($user_pass, PASSWORD_DEFAULT);
$stmt = $con->prepare("SELECT user_name FROM users WHERE user_name = :user_name");
if($stmt->rowCount() > 0){
echo "exists!";
}
}else{
}
I notice 4 things (2 of which have been mentioned by others):
First and smallest is you have a spelling error ($con instead of $conn) - don't worry it happens to the best of us - in you first $stmt query which means your select-results becomes NULL instead of 0 - so you rowCount find that it is not over 0 and moves on without your error message
Second you forgot to bind and execute the parameters in your first $stmt query which gives the same result for your rowCount results
Third always clean your variables even when using prepared statements - at a bare minimum use
$conn->mysql_real_escape_string($variable);
and you can with advantage use
htmlspecialchars($variable);
And fourth since you are not doing anything with the database (other than looking) you could simplify your code by simply writing:
$stmt = $conn->query("SELECT user_name FROM users WHERE user_name = '$user_name' LIMIT 1")->fetch();
as I said - no need to bind or execute in the first query
and as a general rule - don't use rowCount - ever - if you have to know the number of results (and in 99% of cases you don't) use count(); but if you as here just want to know if anything at all was found instead use:
if ( $stmt ) {
echo "exists!";
} else {
// insert new user as you did
}
Edit:
Also - as a side note - there are a few things you should consider when you initially create your connection...
Ex:
// Set variables
$servername = "localhost";
$username = "***";
$password = "***";
$database = "***";
$charset = 'utf8'; // It is always a good idea to also set the character-set
// Always create the connection before you create the new PDO
$dsn = "mysql:host=$servername;dbname=$database;charset=$charset";
// Set default handlings as you create the new PDO instead of after
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // And add default fetch_mode
PDO::ATTR_EMULATE_PREPARES => false, // And ALWAYS set emulate_prepares to false
];
// And now you are ready to create your new PDO
$conn = new PDO($dsn, $username, $password, $opt);
Just a suggestion... happy trails

Fetching database with variable

I'm attempting to have a database pulled with a variable.
$username = $_SESSION['user_username'];
$req = mysql_query("select id, username, message from '$username'_inbox");
while($dnn = mysql_fetch_array($req))
or this..
$username = $_SESSION['user_username'];
$req = mysql_query("select id, username, message from '$username'");
while($dnn = mysql_fetch_array($req))
I just need a solution to fetch a database user related.
mysql_* is deprecated try to use mysqli_*
1) Mysql query should be
select id, username, message from table_name where username='potato'
2) Use prepared statement or PDO when you use user data in query . to avoid sql injection .
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
$stmt = $conn->prepare("select id, username, message from table_name where username=?");
$stmt->bind_param('s',$username);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
$stmt->execute();
$result= $stmt->get_result();
$rows =$result->num_rows;
if($row>0)
{
while($row=$result->fetch_assoc())
{
print_r($row);
}
}
$stmt->close();
$conn->close();

Get sum of row where username is the current user's name

This code just displays a blank webpage. Is there anything wrong with it? It is supposed to show the total points the logged in user has.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "randompassword";
$dbname = "transactions";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT sum(points) AS points FROM transaction WHERE username = '".mysqli_real_escape_string($conn,$_SESSION['username'])."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print($row)
?>
You should enable the error_reporting like this
error_reporting(E_ALL);
ini_set("display_errors", 1);
transaction is a keyword in mysql. So use back tick ( ` ).
Instead of using direct substitution values, you could use below methods to avoid sql injection.
Using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Please refer How can I prevent SQL-injection in PHP?

MySql PHP Update Error

I've been messing about with this code for a few hours now and can't work out why it's not working. It's a profile update php page that is passed through JQuery and all seems to be fine except for it actually updating into the table. Here is the code I'm using:
session_start();
include("db-connect.php");//Contains $con
$get_user_sql = "SELECT * FROM members WHERE username = '$user_username'";
$get_user_res = mysqli_query($con, $get_user_sql);
while($user = mysqli_fetch_array($get_user_res)){
$user_id = $user['id'];
}
$name = mysqli_real_escape_string($con, $_REQUEST["name"]);
$location = mysqli_real_escape_string($con, $_REQUEST["location"]);
$about = mysqli_real_escape_string($con, $_REQUEST["about"]);
$insert_member_sql = "UPDATE profile_members SET id = '$user_id', names = '$name', location = '$location', about = '$about' WHERE id = '$user_id'";
$insert_member_res = mysqli_query($con, $insert_member_sql) or die(mysqli_error($con));
if(mysqli_affected_rows($con)>0){
echo "1";
}else{
echo "0";
}
All I get as the return value is 0, can anybody spot any potential mistakes? Thanks
To begin with, use
require("db-connect.php");
instead of
include("db-connect.php");
And now, consider using prepared statements, your code is vulnerable to sql injections.
Consider using PDO instead of the mysql syntax, in the long run I find it much better to use and it avoids a lot of non-sense-making problems, you can do it like this (You can keep it in the db-connect file if you want, and even make the database conncetion become global):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host, $databaseName, $user, $pass);
Now, here's how you can solve your problem (Using prepared statements, avoiding sql injection):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
You should check the queries though, I fixed them a little bit but not 100% sure if they work.
You can easily make another function which inserts into tha database, instead of updating it, or keeping it in the same function; if you find an existance of the entry, then you insert it, otherwise you update it.

Categories