my select PHP function does not work properly - php

i create a webservice and i call a function to confirm user, but every time i call the function, i receive "registration confirmed" message even if i send the wrong vercode, here is my function implementation, consider ckey is constant and not changable and vercode is changable for every user, i think the problem is about mysql instructions.
// RPC method 2 (confirm user)
function confuser($ckey, $vercode) {
$db = mysql_connect("localhost","root");
if(!$db){
return 'Error: cannot open the connection';
exit;
}
mysql_select_db('user_info');
$query = "select * from personal where vercode='".$vercode."' and ckey='".$ckey."' ";
$result = mysql_query($query, $db);
if($result){
return 'registration confirmed';
}
else{
return 'wrong verification , send it again!';
}
}

You can use something like this:
if(mysql_num_rows($result) > 0){
return 'registration confirmed';
}
else{
return 'wrong verification , send it again!';
}

mysql_query() will return a result handle on ANY successful query. That includes queries that returned ZERO rows. A zero-row result is still a valid result, it just happens to have nothing in it. You will NOT get a "false" return on zero-row queries.
You need to check the number of rows found, e.g.
$result = mysql_query(...);
if (!$result) {
die(mysql_error()); // in case something did blow up
}
if (mysql_num_rows($result) == 0) {
... wrong verification ...
}

mysql_select_db('user_info') or die(mysql_error());
$query = "select * from personal where vercode='$vercode' and ckey='$ckey'";
$result = mysql_query($query, $db) or die(mysql_error());
if(mysql_num_rows($result) > 0)
return 'registration confirmed';
return 'wrong verification , send it again!';
Please note that you need to secure your variables $vercode and $ckey. mysql_real_escape_string() was used to be the escape method, but now mysql_real_escape_string(), and most of the functions you used will be deprecated starting php 5.5.0. Alternatively you can use PDO prepared statements

Related

how to get data from database and save to session array

public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION['email']=$username;
$_SESSION['password']=$password;
}
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}
i have added username and password to my session array but i also want to save id into session array which is stored into databse as "o_id"
You are over complicate the process than necessary. mysql_ extensions are also deprecated.Therefore, you should not use them. use prepare statements which prevent against sql injections. In additional, there is no need for you to store the password in the session. Your password should be stored in the database as hashed so storing it in session wont be reliable to you. Once you find a match against the username and password you searched for, you only need to store the username in the session. In your application, you can compare against the username of logged in area. I modified your code to a much cleaner solution. I had to made few assumptions such as your conn is a PDO.
public function getLoginInfo($username,$password)
{
//start the session only if it has not started somewhere else
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
//try to query the database
try {
$conn = DB::connect();
$sql = 'Select * from owner where o_email= :email and o_password = :password';
$conn->prepare($sql);
$res = $conn->execute(array(':email' => $username, ':password' => $password));
//check if the data exist. only true if result set is greater than 0
if ($res->rowCount() > 0)
{
$_SESSION['email']=$username;
header("location:../owner/owner_dashboard.php");
exit("login success, redirecting to dashboard...");
}
//doesnt exit so go back to login
header("location:../owner/owner_login.php");
exit('Invalid username or password. Redirecting back to lgoin...');
}
//Error is only output for debugging purpose. I would encourage turn this off in production
catch(Exception $e)
{
print_r($e->getMessage());
}
}
First of all, it must be clear that if you are querying for logging
in, then query will return only one row, so using while is
meaningless.
public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Edited from here
// output data of each row
$row = $result->fetch_assoc();
$arraydata[$row['id']] = $row;
$_SESSION['user_info']=$arraydata;
$_SESSION['current_loggedin_id']=$row['id'];
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}

$connection->query($mysearch) not working

The error occurs like that, when i try to connect to DB to search something, it doesn't connects... here is the code below
$connection = new mysqli($db_server,$db_user,$db_pass,$db_name);
if($connection->connect_errno)
{
die ("Connection Failed");
}
$selcap = "SELECT * FROM captcha_codes ORDER BY RAND() LIMIT 1";
$seldcap = $connection->query($selcap);
if($seldcap === true)
{
while ($capdata = $seldcap->fetch_array(MYSQLI_BOTH))
{
$imglink = $capdata['image'];
$idcap = $capdata['id'];
$codecap = $capdata['code'];
}
} else {
$msgreg = "Couldn't connect to Captcha, please contact admin!";
}
The result is Couldn't connect to Captcha, please contact admin!
Use the less strict == comparison here: if($seldcap === true), that should solve the issue.
So the condition would look like: if($seldcap == true)
As mentioned by others, you could also check the number of results as well.
See the docs for mysqli::query() for more information on the results of that function.
If you want to check either query returns result or not use num_rows :
$seldcap = $connection->query($selcap);
if($seldcap->num_rows > 0)
{
//your while stuff
}
else{
//your error stuff
}

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

mysqli_stmt_num_rows, mysqli_stmt_execute and mysqli_store_result

I have the following function which is supposed to check if a new email address to be added into the database is already in there.
function duplicate_email($email_y){
$dbCon = db_connect();
$sql = "SELECT email FROM users WHERE email = ?";
if ($stmt = mysqli_prepare($dbCon, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $email_y);
mysqli_stmt_execute($stmt);
//mysqli_store_result($dbCon);
$rows = mysqli_stmt_num_rows($stmt);
if($rows == 1){
mysqli_stmt_close($stmt);
mysqli_close($dbCon);
return true;
}
else{
mysqli_stmt_close($stmt);
mysqli_close($dbCon);
return false;
}
}
}
This is where I use it:
if(duplicate_email($email) == true){
echo 'Email [ '.$email.' ] seems to be already used';
}
The problem is that is does not detect, I've tested on an email address that is in the database and it fails, it passes over like its not there.
Any thoughts where it fails?
thx
This might not answer your question, but defensive programming style would recommend that you change your statement to if ($rows >= 1) just in case your test email address is included in your database multiple times.
Also, you should handle the case of your if ($stmt = mysqli_prepare...) not returning true. It'll just fall through to the rest of your code and return nothing, which I believe might be interpreted as false. At the very least, print out some debug code (or raise an exception) if that fails.

This if statement isn't working - what am I doing wrong?

I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.

Categories