$connection->query($mysearch) not working - php

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
}

Related

How to check if record is already exists before creating a new record?

I'm trying to implement a duplicate topic blocking system to a forum script. Since I'm extremely poor about PHP I though maybe you'd like to help me. Unfortunately, I'm not even sure if I'm trying to edit the right part of the script but here's the code:
// If it's a new topic
if ($fid)
{
$subject = pun_trim($_POST['req_subject']);
if ($pun_config['o_censoring'] == '1')
$censored_subject = pun_trim(censor_words($subject));
if ($subject == '')
$errors[] = $lang_post['No subject'];
else if ($pun_config['o_censoring'] == '1' && $censored_subject == '')
$errors[] = $lang_post['No subject after censoring'];
else if (pun_strlen($subject) > 70)
$errors[] = $lang_post['Too long subject'];
else if ($pun_config['p_subject_all_caps'] == '0' && is_all_uppercase($subject) && !$pun_user['is_admmod'])
$errors[] = $lang_post['All caps subject'];
}
So I'm trying to implement if $subject is exist in DB (SELECT * FROM topics WHERE subject), show an error in this format: $errors[] = $lang_post['Topic is already exist'];
Thank you.
There are several ways of getting the information that it is in the database or not(here i'm using PDO)
This is the common code:
$conn = new PDO('mysql:dbname=db_name', 'username', 'password')
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
fetch->(PDO::FETCH_NUM)
$sql = $conn->prepare("query_to_db");
$sql->execute();
$rows = $sql->fetch(PDO::FETCH_NUM);
if( $row > 0 ){
echo "the credentials exists";
}
else{
// there is nothing like this in the database
}
mysql error code 23000
try{
// connection code above mentioned
$sql = $conn->prepare("query_to_db");
$sql->execute();
}
catch(PDOException $e){
if($e->getCode() == 23000){
// the credentials exists
}
else{
// doesn't exists
}
}
rowCount()
$sql = $conn->prepare("query_to_db");
$sql->execute();
$count = $sql->rowCount();
if($rowCount > 0){
//exists in the db
}
else{
//it doesn't exists in the db
}
But the rowCount doesn't in mysql
The php doc says:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use DOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
I personally prefer the fetch->(PDO::FETCH_NUM) as it is more precise than the other.

my select PHP function does not work properly

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

PHP $result = mysql_query($query) returns true even if there is no value in database

I have the following code.
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus=$HealthStatus";
$result = mysql_query($query);
echo $HealthStatus;
if($result = false)
{
//do something
}
else
{
//print value already exists
}
I don't get any error or warning when the code is executed. But, even if $HealthStatus exists in database, the if part gets executed. When I give echo $HealthStatus, the value fetched is printed correctly.
I have tried using if(!$result). That doesn't work either. Can someone help me.
You have to use mysql_num_rows to know if the query returned any rows, eg:-
if($result && mysql_num_rows($result))
{
// a row exists
}
else
{
// do something
}
also if HealthStatus is a string it needs to be enclosed in quotes eg:-
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus='".$HealthStatus."'";
$result = mysql_query($query);
if($result && mysql_num_rows($result))
{
// a row exists
$row=mysql_fetch_array($result);
echo "Health status was ".$row["HealthStatus"];
}
else
{
// do something
echo "There were no rows found";
}
To understand how much rows were received use mysql_num_rows function.
if(mysql_num_rows($result) > 0) {
} else {
}
Also, you have error in your if:
if($result = false)
{
//do something
}
else
{
//print value already exists
}
You assign false to $result in your if statement.
You have to use if($result == false).
To avoid such mistakes you can change order:
if(false == $result)
This will work, but this:
if(false = $result)
Will cause error.
Hope, this will help.

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."'";

Displaying a message when resultset is empty

In the following code, if the resultset is empty, the code continues to process the result. What I want instead is to just display "Query failed." when there are no results.
$connInfo = array('UID'=>$user, 'PWD'=>$passwd, 'Database'=>$database);
$dbconn = sqlsrv_connect($server, $connInfo);
if($dbconn === false){
die("<br />Error connecting to the database.<br />");
}
//SQL Query
$query = "SELECT ... FROM somehwere";
//Run Query
$qresult = sqlsrv_query($dbconn, $query);
if($qresult === false) {
die('Query failed.');
}
?>
...more code...
$qresult will contain an empty result set if no rows are found, but it still won't evaluate to false.
Try this function instead:
http://www.php.net/manual/en/function.sqlsrv-num-rows.php
So:
if(!sqlsrv_num_rows($qresult)) {
die('Query failed.');
}
Instead of:
if($qresult === false) {
die('Query failed.');
}
It does not display "Query Failed" because the query has not failed. It just returns 0 rows. So, the solution will be to use:
$row_count = sqlsrv_num_rows( $qresult);
if ($row_count > 0){
// display stuff
}
else{
// throw exception
}
Thanks. I got it to work using sqlsrv_has_rows() function.
if($qresult !== NULL) {
$rows = sqlsrv_has_rows($qresult);
if($rows === true) {
//display success
} else {
//display error
}
}
For some reason I couldn't get the sqlsrv_num_rows() to work properly for me.

Categories