Retrieving value from SQL query - php

It's probably too late, and I'm too tired... but I'm trying to check if a value in my SQL is set to 1 or not. And return true if it is. Been a while since I've done SQL so I'm probably just being stupid...
My code is
$query = mysqli_query($sqlConnect, "SELECT featured FROM al_posts WHERE post_id = {$post_id}");
if ($query->featured == 1) {
return true; }
else {
return false; }

As per the docs:
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You should do:
$query = mysqli_query($sqlConnect, "SELECT featured FROM al_posts WHERE post_id = {$post_id}");
if ($query->fetch_object()->featured == 1) {
return true; }
else {
return false; }
You can read more about mysqli_result here.

Related

PHP isUserAdmin function

I want to read from a MySQL table whether it is an admin. In the row "Status" there is a 1 or a 0. Is it greater than 0 then it is an admin.
PHP:
<?php
if($db->isUserAdmin() === TRUE) {
echo 'Admin';
} else{
echo 'Noadmin';
}
?>
MySQLi:
function isUserAdmin() {
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=:sid");
$stmt->bindParam(":sid", session_id());
$stmt->execute();
if($stmt->rowCount() < 1) {
return true;
} else {
return false;
}
}
Just to educate the great folks of Stack Overflow
function isUserAdmin()
{
$stmt = self::$_db->prepare("SELECT Status FROM users WHERE Session=?");
$stmt->execute([session_id()]);
return $stmt->fetchColumn(); // here is what you really need
}
if($db->isUserAdmin()) {
echo 'Admin';
} else{
echo 'Noadmin';
}
You are checking the number of rows returned by the query, not the value of the status.
If it's admin or user and have a session will always return true because there is an entry in users table. If no user exists will always return false.
You need to check the data returned by sql and check if the value of Status > 0
Or change the sql and add there an extra check that Status > 0

What's wrong in my code??? Update query not working

I'm posting this question after debugging it several times. Please have a look.
<?php
if(isset($_POST["g"]) && isset($_POST["c"]))
{
$g = preg_replace('#[^a-z]#i', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
//echo $g.$c.$log_username;
if($g == "" || $c == "")
{
echo "The form submission is missing values.";
exit();
}
else
{
$sql = "UPDATE users SET gender='$g',country='$c' WHERE username='$log_username'";
$query = mysqli_query($db_conx,$sql);
//echo $query;
$numrows = mysqli_num_rows($query);
//echo $numrows;
if($numrows > 0)
{
echo "success";
exit();
}
else
{
echo "failed";
exit();
}
exit();
}
}
?>
The error i'm getting is
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\sns2\root\account_config.php on line 36
I'm perfectly getting the values of $g,$c,$log_username (tested it using echo). I'm being connected to the database. I don't think there is something wrong with the query syntax because I have manually executed the same query using the values of $g,$c,$log_username. The query was executed. So could be wrong in this?? Please help!!
Citing the php documentation for mysqli_query:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object.
For other successful queries mysqli_query() will return TRUE.
So you're probably getting a TRUE return value and should use http://de3.php.net/manual/en/mysqli.affected-rows.php instead
Use mysqli_affected_rows in case of UPDATE queries.

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in (...) on line 4

Here is my snippet.
I've checked some other questions similar to my error, but so far I can't get it solved.
<?php
function user_exists ($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(user_id) FROM users WHERE username = $username"), 0) == 1) ? true : false;
}
?>
You should split your code in some more lines to handle those errors or special cases. mysql_query will return zero to n rows or an error if it occurs. The returned resource will therefore only be true on non-error queries. This can be used to handle such situations like follows.
At first build and execute query, next process the resource.
$query="SELECT COUNT(user_id) FROM users WHERE username = ".$username;
$result = mysql_query($query);
u may use the following to determine what is going on in case of an error:
if(!$result) die("SELECT failed: ".mysql_error());
or these idea to handle the problem
if (!$result=mysql_query($query)) {
return false; // or similar operation
}
if (mysql_num_rows($result)!=1){
return false;
}else{
return true;
}
This could happen, when mysql_query returns false, if it fails for some reason. So you should split this into multiple statements and check the return values
$sql = "SELECT COUNT(user_id) FROM users WHERE username = $username";
$result = mysql_query($sql);
if ($result === false) {
// error handling
return false;
}
return (mysql_result($result, 0) == 1) ? true : false;

PHP Code Problem

function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
$msg = "true";
}
else
{
$msg = "false";
}
return $msg ;
}
The return value is Object id #1true???? what is object id#1?
Change from:
echo $objUser.check_login($array_login);
to:
echo $objUser->check_login($array_login);
The . operator in PHP does string concatenation, while the arrow allows you to access object methods and attributes.
You're returning the strings "true" or "false" when you probably mean the boolean values true and false.
Oh, and your code is wide open to a visit from Little Bobby Tables. You really should use mysqli and proper prepared statements instead.
Try this:
function check_login($array_val)
{
$strQury = "Select * from tblsignup where usr_email ='".$array_val[0]."' and usr_password = '".$array_val[1]."'" ;
$result = mysql_query($strQury);
$row_user = mysql_fetch_array($result);
if(mysql_num_rows($result)>0)
{
return true;
}
else
{
return false;
}
}
Let us know what result you get when using that code.
user single quotes and things will start to work better. also check your query for sql injection bug as it does have it.
Change
echo $objUser.check_login($array_login);
to
echo $objUser;
echo check_login($array_login);
You should end up with the following result:
Object id #1
true
My guess is that $objUser was set earlier with something along these lines:
$objUser = new User;
As a result, it is an object (the first one declared) and will return Object id #1 when you just echo it. You will need to read up on classes to understand that more.

How to test if a MySQL query was successful in modifying database table data?

I have the following simple php code snippet, which will, when called, delete a relevant article from a database. The result is passed to a javascript function, which will update the page via AJAX. I would like to return the string false if the query fails, as I've below.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
$delRecord->close();
echo "true";
} else {
echo "false";
}
}
I would like to know what I have missed and the correct way to check if a query was successful or not.
You're currently only checking whether the SQL statement is correctly prepared, you're not checking whether it actually deleted the record.
Try:
...
echo ($delRecord->affected_rows > 0) ? 'true' : 'false';
$delRecord->close();
That doesn't address whether you're correctly checking the result string in your Javascript code - if that's a problem we'll need more information.
You need to use mysqli->affected_rows() for checking if the query was successful (or you could use mysqli_stmt->execute()'s result value).
Taking your example, and modifying nothing but for the above:
if($cmd=="deleterec") {
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
if ($delRecord = $con->prepare($deleteQuery)) {
$delRecord->bind_param("s", $pk);
$delRecord->execute();
if ($delRecord->affected_rows > 0) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
}
Use the return value of mysqli_stmt->execute() to see if the query was executed successful.
if($cmd=="deleterec"){
$deleteQuery = "DELETE FROM AUCTIONS1 WHERE ARTICLE_NO = ?";
$delRecord = $con->prepare($deleteQuery);
if ( $delRecord === false ) {
echo "false";
}
$delRecord->bind_param("s", $pk);
if ( $delRecord->execute() ) {
echo "true";
} else {
echo "false";
}
$delRecord->close();
}
Checking prepare() could be left out because the query is fixed and should be working (unless there is an error on the server side). execute() returns true, if the query was executed successful. Using affected_rows() can be misleading because perhaps there was no item to delete and therefore affected_rows() whould return 0. Nontheless the query was successfully executed.
function run_query($query,$conn,$dbname){
$conn->select_db($dbname);
if($result = $conn->query($query)){
return $result;
}
else{
echo 'error ';
exit();
}
}
run_query() accepts three parameters, the query, connection, and DB. will through an error if the query was unsuccessful, else result object will be returned.

Categories