SQLite3 cant fetch columns - php

I wrote my code as simple as possible to make a simple login, because its my first time working with SQLite3 databases.
Here is my code:
<?php
$db = new SQLite3("FirstDatabase.db");
if (isset($_POST['login'])) {
$username = $_POST['user'];
$password = $_POST['pass'];
$query = $db->prepare("SELECT COUNT(`id`) FROM data WHERE `username` = '$username' AND `password` = '$password'");
$query->execute();
$count = $query->fetchColumn();
if($count = 1){
echo "Welcome $username!";
} else {
echo "Wrong credentials";
}
}
?>
I'm really confused why this is not working.. I updated all the extensions etc.
I know this is vulnerable to pretty much every type of attack, but I'm just trying to figure out the SQLite3 database connection.
Thanks! :)
This is the Error I get btw:
Fatal error: Uncaught Error: Call to undefined method SQLite3Stmt::fetchColumn() in C:\XAMPP\htdocs\PHP-Login\index.php:41 Stack trace: #0 {main} thrown in C:\XAMPP\htdocs\PHP-Login\index.php on line 41

The SQL is vulnerable to SQL injection which could be devastating to your database and your system and your health. First and foremost you should change the select to a parametrized query.
There are very good examples in the doc for using a parametrized query and binding the values, not to mention a ton of resource on this site.
The error is telling you that that there is not method fetchColumn() for a SQLite3Stmt object. The PHP: SQLite3Stmt doc confirms that. It is a method on the PDO database extension.

Related

Object returned on mysql_num_rows() function

I am working on a login script with prepared statements in PHP procedural mysqli syntax. Here is my current code:
<?php
include "/ssincludes/functions.php";
$host = HOST;
$username = USER;
$password = PASSWORD;
$db_name = DATABASE;
$table = TABLEU;
//These includes and constants are fine I checked them all
$con = mysqli_connect($host, $username, $password, $db_name);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$myusername='test';
$mypassword='password1';
$sql="SELECT * FROM $table WHERE user_name=? and password=?";
$result=mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($result, 'ss', $myusername, $mypassword);
mysqli_execute($result);
mysqli_stmt_fetch($result);
$row_cnt = mysqli_num_rows($result);
echo $row_cnt;
?>
The error returned is: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, object given
I thought I took out all instances of OO PHP in my script? Also I understand that this may mean my query is incorrect so I ran it on MySQL in the database and all seems to be fine there:
So I am lost as to what the problem could be. I read many similar posts (maybe I'm missing one that is exactly similar to mine) and none seem to handle the problem. I appreciate your time and help.
P.S. I understand the security issues with plain text passwords and using "password1". I plan to use better security practices as I build this but I just want to get prepared statements down first.
You should use
mysqli_stmt_execute
mysqli_stmt_num_rows
Instead of the mysqli_execute and mysqli_num_rows.

PDO connection login [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Would you please help me sort this problem out. I don't know what I'm doing wrong. My connection to database working correct but I'm unable to login.
login.php
<?php
session_start();
$username= $_POST["username"];
$password= $_POST["password"];
include("/inc/connect.inc.php");
if(!isset($conn)){
$conn = null;
header('Location: index.php');
}
else{
$query = $conn->prepare("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password'");
$query ->execute(array(':username' =>$username, ':password' =>$password)
);
if ( ($query->rowCount() == 0) && ( ($password == null) or ($username == null) ) ){
echo "<h3>Please enter your username and password</h3>";
$conn = null;
header("Refresh: 3;URL=index.php");
}
else if ($query->rowCount() == 1)
{
$_SESSION['user_logged'] = $_POST['username'];
unset($username);
unset($password);
echo "<h3>Your password is correct</h3>";
$conn = null;
header("Refresh: 3;URL=interface.php");
}
else {
echo "<h3>The username / password combination entered is incorrect!</h3>";
unset($username);
unset($password);
$conn = null;
header("Refresh: 3;URL=index.php");
}
}
?>
Previously I didn't understand stackoverflow rules. I hope this time my question is more accurate. I have done lot of work to get to this point and only have a problem with login to my database now. My $query = $conn->prepare not finding anything. It's jumping to The username / password combination entered is incorrect! at any time. If I leave username or/and password empty or putting correct username and password always the same result.
I am posting this because it is an answer that addresses the real issue as to why the OP's code isn't working.
Firstly, a typo in bname which should read as dbname in your connection.
Now, you are mixing MySQL APIs with mysql_ functions and PDO.
Those different APIs do not intermix with each other.
In comments you said:
"You are welcome to convert my code to PDO. I can understand that this code is mixed up but have no idea how to fix it."
I don't like coming off as or sounding like the "bad man" here, but that isn't our job to convert your mysql_ code to PDO, it's yours. We don't convert code on Stack, we help out with problematic code.
There are plenty of tutorials out there for you to learn and use.
Here are but a few, which you can further your research on Stack/Google:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
There is also the manuals on PHP.net
http://php.net/manual/en/ref.pdo-mysql.php
http://php.net/manual/en/pdo.query.php
On Stack:
How can I properly use a PDO object for a parameterized SELECT query
Regarding MD5 for passwords:
$password = md5($password);
MD5 is old and considered broken and no longer safe to use for password storage.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
"I'm getting blank screen. Any ideas?"
Regarding "a blank screen".
This means you have syntax errors.
Doing error_reporting(0); means "Turn off all error reporting"
As per the manual on PHP.net
http://php.net/manual/en/function.error-reporting.php
What you need to do is turn error reporting on, not off.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
If you look in the connection string there is a typo:
Take a look at the examples here http://php.net/manual/en/pdo.connections.php
Update: You seem to be totally lost so I'll step by step the code and the reason for things not working. The code I write will be filled with echo and print statements.
1.) You need to check your database connection but you have no code to do this. The connection might be fine but PHP does not throw an error.
try
{
$conn = new PDO('mysql:host=localhost;dbname=' . $database . 'charset=utf8', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(is_object($conn) && $conn != false)
{
echo "I'm connected. PDO is ready and willing";
}
else
{
echo "Sorry something went horribly wrong! Not connected to database";
{
}
catch(PDOException $e)
{
throw new pdoDbException($e);
echo die('Error Message:'.$e->getMessage());
}
2.) It will look like your connection is not working because none of functions is calling a connection. The connection object created is outside of the functions scope.
function user_exists($username)
{
global $conn; // bring the connection object into scope
$username = sanitize($username);
$query = $conn->prepare("SELECT COUNT(user_id) FROM users WHERE username = :username");
$query ->execute(array(
':username' =>$username
));
$user = $query->fetch(PDO::FETCH_ASSOC);
return $user. ' exists in database';
}
3.) there's lots of code but none of the functions looks like they are being called at runtime. Test for user exists and if database connection works at runtime in the init.php file
<?php
session_start();
require 'database/connect.php';
require 'functions/general.php';
require 'functions/users.php';
$errors = array();
// call a function to check if user exists.
echo user_exists('user_123');
?>
1st step. Change
$conn = new PDO('mysql:host=localhost;bname='.$database.'charset=utf8',$username,$password);
to
$conn = new PDO('mysql:host=localhost;dbname='.$database.';charset=utf8',$username,$password);
2st. You use mysqli and pdo in one project. For what?

PHP binding error

I'm trying to use this script to see if there's a registered using in my database, but I'm having trouble on line 6. I keep getting the error:
Fatal error: Call to a member function bind_param() on a non-object in
-redacted-/check_login.php on line 6
I'm stumped as to why it's failing, because I have a similar statement working on the create user function.
<?php
ini_set('display_errors', 'On');
$db = new mysqli("localhost", "root", "-redacted-", "-redacted-");
$query = $db->prepare("SELECT user FROM users WHERE username = ? AND password = ?");
$query->bind_param('ss', $_POST['username'], md5($_POST['password']));
$query->execute();
$query->bind_result($result);
$query->fetch();
if($result->num_rows == 1) {
session_start();
$_SESSION['user'] = $_POST['username'];
header("Location: 10.0.0.15/index.php");
}
?>
This is usually caused by referencing a non-existant column/table in your database schema. Hence why the prepared is the root cause of this error.
What you should do, is check over your query. Making sure you are:
not using reserved mysql keywords
referencing columns/tables that
exist within the schema
There are no syntax errors within your SQL
Query

PHP undefined index error in communicating with android

I am retrieving data from a database in android so created a php file as below.
<?php
$db_host = "localhost";
$db_uid = "root";
$db_pass = "";
$db_name = "abc";
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM people WHERE birthyear > '". $_POST["birthyear"]."'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Now when i run it in the browser as localhost/script.php
error is thrown and the output is displayed as below
Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14
[{"id":"1","name":"m","sex":"1","birthyear":"1989"},{"id":"2","name":"a","sex":"1","birthyear":"1986"},{"id":"3","name":"b","sex":"0","birthyear":"1986"}]
Please tell me how to correct my code.
$output[]=array("key"=>$row['field_name'],"key1"=>$row['field_name2']);
store array like this
You are directly inserting $_POST["birthyear"] in your query which makes you vulnerable to SQL injection. Stop doing it right now!
That is also why you get the error. When you directly call the script in your browser, that will be with a GET request and there wont be any POST variables available. So your $_POST array wont have a key for birthyear and thus it warns you about it.
You should start with something like
<?php
$by = isset($_POST["birthyear"]) ? $_POST["birthyear"] : "";
if (empty($by)) {
echo 'Invalid birthyear';
exit;
}
//SANITIZE YOUR BIRTHYEAR HERE
//in this case, probaly check for a integer between 1900 and 2100 or something.
//Although just an int could be enough to prevent injection
if (!is_int($by)) {
echo 'You failed to provide a valid year';
exit;
}
$sql = "SELECT * FROM people WHERE birthyear > '". $by."'";
//execute the code
?>
Although the above code is safe, you should check out bound parameters like used in mysqli prepared statements or PDO
you probably failed to send the values trough post properly.
try print_r($_POST); to see what you are actually sending
you still get all results because every year is > ''

PHP mysql query syntax errors

I'm fairly new to PHP/MySQL and I seem to be having a newbie issue.
The following code keeps throwing me errors no matter what I change, and I have a feeling it's got to be somewhere in the syntax that I'm messing up with. It all worked at home 'localhost' but now that I'm trying to host it online it seems to be much more temperamental with spaces and whatnot.
It's a simple login system, problem code is as follows:
<?php
session_start();
require 'connect.php';
echo "Test";
//Hash passwords using MD5 hash (32bit string).
$username=($_POST['username']);
$password=MD5($_POST['password']);
//Get required information from admin_logins table
$sql=mysql_query("SELECT * FROM admin_logins WHERE Username='$username' ");
$row=mysql_fetch_array($sql);
//Check that entered username is valid by checking returned UserID
if($row['UserID'] === NULL){
header("Location: ../adminlogin.php?errCode=UserFail");
}
//Where username is correct, check corresponding password
else if ($row['UserID'] != NULL && $row['Password'] != $password){
header("Location: ../adminlogin.php?errCode=PassFail");
}
else{
$_SESSION['isAdmin'] = true;
header("Location: ../admincontrols.php");
}
mysql_close($con);
?>
The test is just in there, so I know why the page is throwing an error, which is:
`Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in 'THISPAGE' on line 12`
It seems to dislike my SQL query.
Any help is much appreciated.
EDIT:
connect.php page is:
<?php
$con = mysql_connect("localhost","username","password");
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
?>
and yes it is mysql_*, LOL, I'll get to fix that too.
You should escape column name username using backtick, try
SELECT *
FROM admin_logins
WHERE `Username` = '$username'
You're code is prone to SQL Injection. Use PDO or MYSQLI
Example of using PDO extension:
<?php
$stmt = $dbh->prepare("SELECT * FROM admin_logins WHERE `Username` = ?");
$stmt->bindParam(1, $username);
if ($stmt->execute(array($_GET['name']))) {
while ($row = $stmt->fetch()) {
print_r($row);
}
}
?>
Sean, you have to use dots around your variable, like this:
$sql = mysql_query("SELECT * FROM admin_logins WHERE Username = '". mysql_real_escape_string($username)."' ");
If you use your code just like this then it's vulnerable for SQL Injection. I would strongly recommend using mysql_real_escape_string as you insert data into your database to prevent SQL injections, as a quick solution or better use PDO or MySQLi.
Besides if you use mysql_* to connect to your database, then I'd recommend reading the PHP manual chapter on the mysql_* functions,
where they point out, that this extension is not recommended for writing new code. Instead, they say, you should use either the MySQLi or PDO_MySQL extension.
EDITED:
I also checked your mysql_connect and found a weird regularity which is - if you use " on mysql_connect arguments, then it fails to connect and in my case, when I was testing it for you, it happened just described way, so, please try this instead:
$con = mysql_connect('localhost','username','password');
Try to replace " to ' as it's shown in the PHP Manual examples and it will work, I think!
If it still doesn't work just print $row, with print_r($row); right after $sql=mysql_query() and see what you have on $row array or variable.

Categories