PHP MySQL Update Query Failing [duplicate] - php

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 6 years ago.
I'm trying to execute the following query to update a record in a table.
require "conn.php";
$user_name = $_POST["username"];
$code = $_POST["code"];
$name = $_POST["groupname"];
echo "$user_name, $code, $name";
$sql_update = "UPDATE users SET group = '$name' WHERE username = '$user_name'";
if ($conn->query($sql_update) === TRUE) {
echo "success";
}
else {
echo "fail";
}
The query fails and I'm not sure why. The connection is made and I'm able to echo the username code and name. Is there a reason why it's not working?

Your code is not secure
Look at this code with prepared statements
require_once("conn.php");
$user_name = $conn->real_escape_string($_POST["username"]);
$code = $conn->real_escape_string($_POST["code"]);
$name = $conn->real_escape_string($_POST["groupname"]);
$sql_update = $conn->prepare("update `users` set `group` = ? where `username` = ?");
$sql_update->bind_param("ss",$name,$user_name);
$sql_update->execute();
$sql_update->close();
$conn->close();
And conn.php file should be like this
$config = parse_ini_file('config.ini'); // Connection infos.
$conn = mysqli_connect('localhost',$config['username'],$config['password'],$config['db_name']);
if($conn === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$conn->set_charset("utf8");
Create file outside the public_html folder named config.ini to write connection data
[db_connection]
username = username
password = password
db_name = dbname
This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string.
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
Learn more here

Related

Connect SQLite using PDO to create a login page

I am trying to create a login page using SQlite. However, for some reason I have been getting error (
Fatal error: Uncaught Error: Call to a member function fetch() on boolean in C:\xampp\htdocs\project\login.php:20 Stack trace: #0 {main} thrown in C:\xampp\htdocs\project\login.php on line 20)
<?php
include("config.php");
session_start();
$error = "";
if(#$_SESSION['login_user'] != null){
header("location: dashboard.php");
}
if(!empty($_POST['username']) && !empty($_POST['password'])) {
// username and password sent from form
$myusername = strtolower($_POST['username']);
$mypassword = $_POST['password'];
$dir = 'sqlite:db.sqlite3';
$dbh = new PDO($dir) or die("cannot open the database");
$sql = "SELECT username, password FROM users_ WHERE username = '$myusername' and password = '$mypassword'";
$result = $dbh->query($sql);
$row = $result->fetch();
echo $row['username'];
echo $row['password'];
}
?>
From the PHP doc: PDO::query() returns a PDOStatement object, or FALSE on failure. That means $dbh->query($sql) could return a boolean (false) if something went wrong with executing your SQL query (you should add code to handle this possibility). The error message you got strongly suggest this is the case.
So, let's see, what could be the cause of your SQL failing. These are possibilities ...
Is your table name really "users_" (note the trailing underscore) or should it be just "users".
Maybe the value of $password contains a character, like ' (single quote) that would result in a bad SQL statement.
UPDATE (to answer comment below): You are building the entire SQL statement including data values all in PHP as a string before PDO sees it. So PDO only sees the string and so it cannot know or handle special characters that should be escaped. PDO would have to be waaaay too smart to know which characters are okay and which are not (especially if the data is an SQL injection; it would look just fine if PDO parsed it looking for characters to escape).
As it is, your code is exposed to SQL injection. You should either 1) escape the data ...
$sql = "SELECT username, password FROM users_ WHERE "
. "username = '" . $dbh->quote($myusername) . "' "
. "and password = '" . $dbh->quote($mypassword) . "'";
or (MUCH BETTER!) 2) use prepared statements (PDO will do any necessary escaping as it substitutes data values for the ? in the SQL statement)
$sql = "SELECT username, password FROM users_ WHERE "
. "username = ? AND password = ?"; // note the "?" placeholders
$stmt = $dbh->prepare($sql);
$stmt->execute([$myusername, $mypassword]); // here, PDO will escape characters
while ($row = $stmt->fetch()) {
// process a $row
}

PHP 7.1 query for User check gives out a Warning: A non-numeric value encountered in E:\XAMPP\htdocs

I'm facing a weird problem, I'm trying to implement a simple Usercheck with PHP 7.1.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//checking if nickname already exists
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
//sending query to sql database
$doesExist = mysqli_query($con, $checkUserExistanceSql)
or die ("Fehler in der Datenbankabfrage");
if(mysqli_num_rows($doesExist)>=1){
echo "Nickname not available, use another name";
}
But I'm getting this warning
Warning: A non-numeric value encountered in E:\XAMPP\htdocs... Line 29
Line 29 is the $checkUserExistanceSql. Any ideas where the problem is?
String concatenation on PHP uses . (dot) as operator, not + (plus).
You actual code uses +:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" + $nickname+ "'";
This is why PHP is telling that $nickname isn't a numeric variable. It cannot sum strings, only concatenate.
Change your operator to . and it will work:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='" . $nickname . "'";
You can also use this syntax, with the same result but cleaner code:
$checkUserExistanceSql = "SELECT nickname FROM user WHERE nickname='{$nickname}'";
Security Alert
You code is sucessive to SQL injection. You should use prepared statements instead of concatenating your variables into the Query.
Thanks to the help of Yolo and Elias Soares.
The script runs flawless now, I also used prepared statement to counter the risk of sql injection as mentiones by elias.
$con = getConnection();
//check connection
if(!$con){
die("Connection to database failed". mysql_connect_error() );
} else echo ("connection to database successfull");
//prepared statement for sql query
$stmt = $con -> prepare("SELECT nickname FROM user WHERE (nickname=?)");
$stmt -> bind_param("s", $nickname);
$stmt->execute();
//checkking result, if nickname is already used
if($stmt->get_result()){
echo "0";
} else {
//insert user
}

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

how to store mysql select statement inside php variable using mysqli

I know this has been asked before but I cant seem to fix my code.
What I need is to run some php code to query mysql using mysqli for a select statement to retrieve my bcrypt hashed pass so I can compare the user input with the user hashed password. NOTE: I have not yet added mysql_real_escape_string to my $POST variables.
I've changed this code a thousand times still cant get it.
Ive even copy and pasted to a new file a simple query script using num_row
and printf($row['pass']); used echo etc..... I've used fetch array ive tried almost everything I've been all via php mysql at php.net w3c.com etc etc is my system broke? Does mysqli have a bug ? and no i dont want to switch to PDO I wont stop til this is fixed and when there is no longer sql injection vulns
Heres my code:
<?php
$conn = new mysqli('localhost', 'root', '', 'social');
if (mysqli_connect_errno())
{
exit("connection failed" . mysqli_connect_error());
}
else
{
echo "connection established";
}
$db=mysqli_select_db( $conn,'social');
if ($_POST && isset($_POST['submit'], $_POST['password'], $_POST['email']))
{
$pass = ($_POST["password"]);
$email =($_POST["email"]);
$bcrypt = password_hash($pass, PASSWORD_BCRYPT, array('cost' => 12));
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
echo $fetcher;
if ($conn->query($fetcher) === TRUE)
{
echo "query has gone through now we need to store the hash<br /> for comparison";
}
else
{
echo "error did not retrieve hash info";
}
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$fetcher = mysqli_fetch_assoc($query);
Before you can fetch records from the result of the query, you need to actually perform the query. Your code should be
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$result = $conn->query($query); // This is where the query is executed
$fetcher = $result->fetch_assoc();
Two more points.
First, you don't need to call mysqli_select_db; you've already selected the database in your constructor call, so you only need to call mysqli_select_db if you want to access a different database.
Second, instead of calling mysql_real_escape_string you should look into using prepared statements, which do the same thing and also correctly handle type-matching and quoting.
Try fetching the value from database after executing the query
$query = "SELECT `pass` FROM `social` WHERE `email` = 'jargon#jargon'";
$executedQuery = $conn->query($query);
if($executedQuery) {
$fetcher = mysqli_fetch_assoc($executedQuery);
echo "query has gone through ---------";
} else {
echo "error did not retrieve hash info";
}
$query = "SELECT pass FROM social WHERE id = 11"; // took the (``) out of the query and added this im assuming the value is stored in the $row variable and I may be able to use $row with the user input to verify hash via bcrypt!!!
$result = $conn->query($query);
while($row = mysqli_fetch_array($result))
{
echo $row['pass'];
echo "<br />";
}

How do I check if a user already exists in an SQL database? [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I am trying to test a simple user account registration page for a project for class, and I am trying to create a check that will notify the user if their email is already in the database, and therefore will not add them to it again. Here's my PHP code.
<?php
$collegeid = mysql_real_escape_string('1');
$email = mysql_real_escape_string('abc#test.com');
$password = mysql_real_escape_string(md5('test1'));
$name = mysql_real_escape_string('Test Test');
$bday = mysql_real_escape_string('1900-01-01');
$class = mysql_real_escape_string('Freshman');
//echo "<p>Test</p>";
$servername = "localhost";
$username = redacted;
$serverpassword = redacted;
$dbname = redacted;
$conn = new mysqli($servername, $username, $serverpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$checkquery = "SELECT * FROM Student WHERE Email = '$email'";
$insertquery = "INSERT INTO Student (CollegeID, Name, Birthday, Email, Classification, Password) VALUES ('$collegeid', '$name', '$bday', '$email', '$class', '$password')";
if (mysql_num_rows($conn->query($checkquery)) > 0)
{
echo "Error: Email already in use";
}
else
{
$conn->query($insertquery);
echo "Account Created.";
}
?>
However, it always tells me the account is created, regardless of whether or not that user is in the database.
You are mixing mysql and mysqli functions. You should not use mysql functions as they are deprecated and you seem to be using mysqli for almost everything except escaping your values and checking the number of found rows.
The problem is caused by your use of mysql_real_escape_string. When no mysql_* database connection is found, that returns false which is the equivalent of an empty string so you are checking for empty values in your database and everytime you don't find that, you add a new row.
To secure yourself against sql injection on mysqli, you should switch to prepared statements instead of using mysqli_real_escape_string.
Edit: It is also mysql_num_rows that is returning false in case of an error...

Categories