This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I am trying to do something new in PHP, counting rows in a MYSQL database.
But it keeps spitting out errors as soon as I put echo $rows in it.
Can someone please help me?
Here is my login code.
<?php
'include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
// if (DB::query('SELECT token FROM login_tokens WHERE user_id=1')<=5) {
if (password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=> $username))[0]['password'])) {
echo 'Logged in!';
$query = DB::query('SELECT * FROM login_tokens WHERE user_id=:user_id', array(':user_id'=>$user_id));
$rows = mysql_num_rows($query);
echo $rows;
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
DB::query('INSERT INTO login_tokens VALUES (0, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("SNID_", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
} else {
echo 'Incorrect Password!';
}
// } else {
// echo 'You already logged in on 5 different devices!'
// }
} else {
echo "User not registered! Create account <a href='http://follome.ddns.net/create-account.php'>here</a>!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username ..."><p />
<input type="password" name="password" value="" placeholder="Password ..."><p />
<input type="submit" name="login" value="Login">
</form>
And my DB class:
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=socialnetwork;charset=utf8', 'root', 'Daan0109');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement-> execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
You can't mix the db extensions (PDO, mysqli, mysql). Furthermore, mysql was deprecated and is removed in php7.
You should use the PDO variant of mysql_num_rows()
http://php.net/manual/de/pdostatement.rowcount.php
But you need the PDOStatement object to call this. Otherwise, if you always return fetchAll(), you can just use a simple count()
It's because you use PDO, so you should check the row number with its rowcount.
http://php.net/manual/en/pdostatement.rowcount.php
Also, I would suggest you to use a framework or at least an ORM to support your goals, because otherwise you will waste a lot of time implementing features, which are aleady done. For ORM I think Doctrine is a good choice, and Laravel is an easy-to-start framework. I hope I could help you.
Related
I have been working on a website on a localhost and have just tried to upload it to a free webserver so I can get some testers, for some reason my code is being reported as malware and is being blocked by my antivirus, this means I can't see anything when visiting it apart from the ERR_CONNECTION_RESET. Have you guys got any ideas as to why this code is being detected as malware?
LOGIN.php
<?php
include('classes/db.php');
if (db::maintenance()) {
die('This site is currently going under maintenance, please check back again shortly.');
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (db::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
if (password_verify($password, db::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) {
echo "Logged in!";
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = db::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
db::query('INSERT INTO login_tokens VALUES (NULL, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie('SNID_', '1', time() + 60 + 60 * 24 * 3, '/', NULL, NULL, TRUE);
header('Location: index.php');
} else {
echo "Incorrect password";
}
} else {
echo "User not registered!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username"><p />
<input type="password" name="password" value="" placeholder="Password"><p />
<input type="submit" name="submit" placeholder="Login"><p />
</form>
DB.php
(I have changed the connection to false data, and changed it to the correct data when uploading it to the host.)
<?php
class db {
private static function connect () {
$conn = new PDO('mysql:host=localhost;dbname=users;,charset=utf8', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
public static function query ($sql, $params = array()) {
$statement = self::connect()->prepare($sql);
$statement->execute($params);
if (explode(' ', $sql)[0] == 'SELECT') {
$result = $statement->fetchAll();
return $result;
}
}
public static function notify ($userid) {
$notifications = db::query('SELECT forum_members.forum_id, notifications.user_id, notifications.post_id, notifications.forum_id, notifications.post_body, notifications.creation, notifications.type FROM forum_members, notifications WHERE (notifications.forum_id=forum_members.forum_id OR notifications.forum_id=0) AND notifications.user_id=forum_members.user_id ORDER BY notifications.post_id DESC');
return $notifications;
}
public static function maintenance () {
return false;
}
}
?>
Which type of address do you use to enter the website? PHP source doesn't display to browsers, so PHP isn't the problem.
If you enter in with a hostname (Ex. .....2cc.brad....net) Then it'll automatically get detected as a "malware" for beginner safety, if ur accessing it from localhost/127.0.0.1 it should be fine, but if ur accessing it from a host that's marked as malware, than yep.
This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 7 years ago.
Hello I have while adding a login user I want to check if this user is already in DB, it will display a message if not it will be added to DB:
This is the form in html:
<form name="inscription" method="post" action="03insert.php">
login: <input type="text" name="login" value=""/>
<input type="submit" name="submit" value="Inscription"/>
</form>
And this the code in PHP:
<?php
$connection = ConnectionBD();
if( isset($_POST['submit']) ){
$login = $_POST['login'];
$sql_1 = "SELECT * FROM users WHERE user_login = :login";
$query = $connection->prepare($sql_1);
$query->bindParam(':login', $login, PDO::PARAM_STR);
$query->execute();
$count = $query->rowCount();
if ($count > 0){
echo 'This login already exist';
}
else
{
$sql_2 = 'INSERT INTO users VALUES(null,"'.$login.'")';
$result = $connection->exec( $sql_2 );
if( $result > 0 ){
echo 'Registered successfully';
}else{ echo 'ERROR !<br><br>'; }
}
}
unset( $connection );
?>
I don't have error but It add the user even its exist ..Please help!!
Your first line of code, you use this:
$connection = ConnectionBD();
Why is there no new keyword or is it a standard function? If it's a class you need to instantiate it, i.e.:
$connection = new ConnectionBD();
// OR
$connection = ConnectionBD()::initFunction(); // If it's static
You won't get a thang from it as the object is not instantiated properly
Try to change your query to this:
$sql_1 = "SELECT * FROM users WHERE user_login = :login";
//just removed the single quotes '
This question already has an answer here:
Get results from from MySQL using PDO
(1 answer)
Closed 7 years ago.
I'm totally new to PDO so I apologize if I made a simple mistake here. Also if this has been answered before. I searched but couldn't find. My problem is that when I print the sessions it prints out 'Array ( [user_id] => 1 )' but the username and password I entered is for user_id 2. I have tried this with a differant username and password and it still gives an id value of 1. So I echoed out $user_id before the session is created and it is 1. But I can't figure out where it is getting this 1 from? Because there is no id of 1 in the database. Can anyone shed some light on this?
Here is the code from my login file:
<?php
require 'core.inc.php';
if(isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
$stmt = $db->prepare("SELECT password FROM users WHERE username = ?");
$stmt->bindParam(1, $username);
$hash = $stmt->execute();
$password_verified = password_verify($password, $hash);
if ($password_verified = true) {
$stmt_id = $db->prepare("SELECT id FROM users WHERE username = ?");
$stmt_id->bindParam(1, $username);
$user_id = $stmt_id->execute();
echo $user_id;
$id_num_rows = $stmt_id->rowCount();
if ($id_num_rows == 0) {
echo 'You have entered a wrong password';
}else if($id_num_rows == 1){
$_SESSION['user_id'] = $user_id;
print_r($_SESSION);
}
} else {
echo("Please enter a username and password.");
}
}
}
?>
<!DOCTYPE html>
<header>
</header>
<body>
<form action ="<?php echo $current_file;?>" method="post">
<div class='field'>
<label for="username">Username: </label><input type='text'
name='username'/><br>
</div>
<div class='field'>
<label for ="password">Password: </label><input type='password'
name='password'/>
</div>
<div class='field'>
<label for='remember'>
<input type='checkbox' name="remember" id="remember"/> Remember me
</label>
</div>
<input type='submit' value='Log in'/>
</form>
</body>
</html>
<And here is the code from core.inc.php
<?php
session_start();
require 'connect.inc.php';
ob_start();
$current_file = $_SERVER['SCRIPT_NAME'];
#$http_referer = $_SERVER['HTTP_REFERER'];
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])) {
return true;
}else{
return false;
}
}
?>
<Core.inc.php uses connect.inc.php which is added below:
<?php
try {
$db = new PDO('mysql:host=localhost;dbname=goal;charset=utf8','root','');
var_dump($db);
echo 'connected';
}
catch(Exception $e){
echo 'Error 1 has occured';
}
?>
$stmt_id->execute();
Returns true on succes, or false on failure, you need to use the result of the query (and not the status of the execution):
$stmt_id->fetchAll()
Also you have an error here, you need to use comparison and not assignment:
if ($password_verified = true)
The line
if ($password_verified = true) {
is very incorrect because you're basically just assigning true to $password_verified. You should just be doing a if($password_verified) though, I am not sure if it will solve your problem.
You are also not parsing the results as you should be using fetchAll() and then going through the results to see if the user exists.
$stmt_id->execute() will return bool, in your case it's true and later converted to int.
See http://php.net/manual/en/pdostatement.execute.php
You need to fetch the data in order to retrieve the user_id.
Coding, as I've been learning, is about little details, and I'm missing something because I have the following code:
public function login() {
if ($_POST) {
$logdb = new PDO('mysql:host=localhost;dbname=kiko', 'kiko', 'pass');
$logdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $logdb->prepare("SELECT * FROM usreg WHERE email=:email AND password=:pass");
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":pass", $_POST['password']);
$stmt->execute();
$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_ASSOC);
if ($loged) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
$_SESSION["email"] = $_POST['email'];
$_SESSION["group"] = $atributes->group;
$_SESSION["firstname"] = $atributes->firstname;
$_SESSION["lastname"] = $atributes->lastname;
$_SESSION["phone"] = $atributes->phone;
$_SESSION["mobile"] = $atributes->mobile;
$_SESSION["adress"] = $atributes->adress;
$_SESSION["city"] = $atributes->city;
$_SESSION["country"] = $atributes->country;
} else {
echo 'wrong login try again';
}
} else {
echo '<form name="login" action="" method="POST">
Email: <br />
<input type="text" name="email"/><br />
Password: <br />
<input type="password" name="password"/><br />
<button type="submit">Login</button>
Register</form>';
}
}
and everything works well except the part where I'm registering globals. What I'm trying to do is set the global session the details from the fetch array atributes, I tried with:
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
but the result is the same, and I changed the email from array to POST and it works because when I do:
echo $_SESSION['email'];
It works, but the fetch is not passing the details to the other session globals. What should I put in there to sucess what I'm trying to do can you guys help me? Do I need another kind of prepared statement? Is it missing results because I'm making the WHERE clause?
Why are you fetching twice? Once for $loged and another for $atributes
I assume the username/password combination will be unique, so you'll only get one result from your SQL query. That means when you call fetch again, you'll get nothing.
Perhaps you want:
//$loged = $stmt->fetch();
$atributes = $stmt->fetch(PDO::FETCH_OBJ);
if ($atributes) {
session_start();
$_SESSION["loggedIn"] = true;
$_SESSION["id"] = $atributes->id;
Also, make sure you use password_verify when dealing with passwords!
I have a simple account creation script that is not working. I know that there are no connection errors because the login works fine. Also, I turned on error-reporting (made it -1) but it shows no errors
This is my code in snippets, thanks
HTML
<form method="post">
<input type="text" name="newUsername" placeholder="Username"/>
<input type="password" name="newPassword" placeholder="Password"/>
<input type="submit" name="signUp" value="Sign Up!"/>
</form>
Then PHP:
if($_POST['signUp']) {
$username = $_POST['newUsername'];
$pass = $_POST['newPassword'];
$signedUp = SignUp($Username,$pass);
echo $signUpCode[$signedUp]; // See the SignUp function in prefunc.php
} elseif($_POST['LogIn']) {
$username = $_POST['Username'];
$password = $_POST['Password'];
$loggedIn = LogIn($username,$password);
echo $logInCode[$loggedIn];
}
$signUpCode = Array(
"-3"=>"Logged in already - can't sign up!",
"-2"=>"Username already exists!",
"-1"=>"Failed to sign up - please try again!",
"1"=>"Signed up, and logged in successfully!"
);
function SignUp($Username,$Password) {
$Username = preg_replace("/[^a-zA-Z0-9]/","",$Username);
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(getCurrentId()){
return -3;
}
if(!mysql_num_rows($u)) {
mysql_query("INSERT INTO Users SET Username='$Username',Password=''$Password") or die(mysql_error());
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(mysql_num_rows($u)) {
LogIn($Username,$Password);
return 1;
} else {
return -1;
}
}
return -2;
}
Are you sure you re executing the insert query?
also the query sintax is wrong, try this: insert into user ( username,password) values ('admin','1234').
finally you must fix security issue, your code is affected by sql injection