I want to make a input box where first check duplicate category. If it find a duplicate category then it return false but if it don't find duplicate then insert new category name into database.
It check duplicate properly and insert category properly but show this error:
Catchable fatal error: Object of class mysqli_result could not be converted to
string in C:\wamp\www\ecommerce\class\category.php on line 23
Call Stack
# Time Memory Function Location
1 0.0006 137488 {main}() ..\catadd.php:0
2 0.0146 176512 Category->insertCat() ..\catadd.php:15
Here is the method that causes the error:
public function insertCat($catName)
{
$catName = $this->fm->validation($catName);
$catName = mysqli_real_escape_string($this->db->link, $catName);
if(empty($catName)){
$msg = 'Cat name can not empty';
return $msg;
}else{
$dcatName = "select * from tbl_category where catName='$catName'";
$rowCount = $this->db->select($dcatName);
$catRow = mysqli_num_rows($rowCount);
if( $catRow > 0 ){ /* <---- Line 23 ----- */
echo 'Cat Name already Exist';
}else{
$query = "INSERT INTO tbl_category (catName) VALUES ('$catName')";
$catResult= $this->db->insert($query);
if($catResult){
$msg = 'Cat name Updated';
return $msg;
return $msg;
}else{
$msg = 'Not updated';
return $msg;
}
}
}
}
The select method looks like:
// Select or Read data
public function select($query){
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows > 0)
{
return $result;
}
else
{
return false;
}
}
On compilation, I got this warning:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\ecommerce\class\category.php on line 22 ( $catRow = mysqli_num_rows($rowCount); is line 22)
Considering your select method looks like this:
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows > 0){
return $result;
} else {
return false;
}
}
...this method already checks number of rows so this row:
$catRow = mysqli_num_rows($rowCount);
...is not needed, furthermore, causes an error if the select() method returns no rows, it returns false which will produce the error when you try to reference a method from a false return. You should be able to just do:
# This will either return the resource or false so you don't need
# to count rows
$rowCount = $this->db->select($dcatName);
if($rowCount) {
EDIT:
One point I should make is that you should probably modify your select() method (and any other query methods you have) to accept an array as a second parameter. That second array should let the method know that you need to bind_param so you can use that feature. This may be an SQL Injection vulnerability:
$dcatName = "select * from tbl_category where catName='$catName'";
Related
I have a function to find a product name from Id. If there is a product for that ID I assign that name to $name variable. Otherwise I have a another code to run.
I have following code to do it. it works fine.
But I saw today it is a bad practice return two data types even it allows in PHP.
Without return two datatypes how I do it?
if(!findProductName($id,$con))
{
// Some code....
}
else
{
$name=findProductName($id,$con);
}
function findProductName($pro_id,$con){
$sql="SELECT pro_name FROM product WHERE `pro_id`=".$pro_id." limit 1";
$select_result = mysqli_query($con,$sql);
if(mysqli_num_rows($select_result) > 0){
$pro_row = mysqli_fetch_array($select_result,MYSQLI_ASSOC);
return $pro_row['pro_name'];
}
else{
return false;
}
}
You can return empty string:
function findProductName($pro_id,$con){
$sql="SELECT pro_name FROM product WHERE `pro_id`=".$pro_id." limit 1";
$select_result = mysqli_query($con,$sql);
if(mysqli_num_rows($select_result) > 0){
$pro_row = mysqli_fetch_array($select_result,MYSQLI_ASSOC);
return $pro_row['pro_name'];
}
else{
return '';
}
}
Here's my code:
<?php
$con = mysqli_connect("127.0.0.1:3306","root","root","photoshare");
$query = "SELECT ID,nickname,photoLikes FROM tbl_photo";
$result = mysqli_query($con,$query);
$query_dislike = "SELECT nickname, idGivenLike FROM tbl_check_like";
$resultDislike = mysqli_query($con,$query_dislike);
$photoIDdislike;
$photoID;
while($photoID = mysqli_fetch_assoc ($result) || $photoIDdislike = mysqli_fetch_assoc($resultDislike) )
{
//checks if both of results
if($result["ID"] != $resultDislike["idGivenLike"])
{
echo "true";
}
}
?>
When I run it it's says that the next line
if($result["ID"] != $resultDislike["idGivenLike"])
With h Fatal error: Fatal error: Cannot use object of type mysqli_result as array
why it's doesnt work and how may i fix it?
if($result["ID"] != $resultDislike["idGivenLike"])
Should be:
if($photoID["ID"] != $photoIDdislike["idGivenLike"])
$resultDislike/$result is your MySQL resource, $photoID/$photoIDdislike is the fetched row (array).
It should be
$photoID["ID"] != $photoIDdislike["idGivenLike"]
// In script
if($photoID["ID"] != $photoIDdislike["idGivenLike"])
{
echo "true";
}
I was writing the php to query the MySQL DB, but the sql sentence works sometimes but failed sometimes .**when it works, it will return records, when it failed it will say: **You have an error in your SQL syntax. I don't know how to fix it,please give me a hand.thanks.the *_id and type is integer,others are string or date type.
function getMyAwardRecords()
{
global $db, $userId, $nickName;
$result0 = $db->fetchrows("SELECT user_nick,type,create_date FROM records WHERE type=0 AND user_id={$userId}");
// echo $userId;
$result = $db->fetchrows("SELECT records.user_nick, records.type, records.create_date, awards.code FROM records, awards WHERE records.award_id = awards.award_id AND records.user_id = {$userId}");
$result = array_merge($result, $result0);
// print_r($result);
if($result)
{
echo ajaxResponse(200,$result);
}
else
{
echo ajaxResponse(400);
}
}
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;
I want to use my own error handling and my first thought was this:
// db connection
$conn = conn();
if(!$conn)
$aErrors[] = 'Fout: Geen database verbinding!';
function db_error($conn)
{
if(mysql_errno($conn) == 0)
return true;
else
{
// log! and global $aErrors[] = mysql_errno($conn)
return false;
}
}
$q = "SELECT
xusername, email
FROM
terra_user
WHERE
ID = '".$_GET['ID']."'
LIMIT 1";
$exec = mysql_query($q);
// error check
if(db_error($exec))
{
echo'teeeeeest!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
But I get the next error:
Warning: mysql_errno(): supplied argument is not a valid MySQL-Link resource in xxxx
In this case, mysql_erro() returns a number > 0, so it looks OK, except that the link source is not OK?
If I use mysql_errno($conn) I get :
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in xxxxxx
In this case, mysql_erro() returns 0!
For this code I have changed one field with a wrong name. Put an extra x for username:)
$_GET['ID'] is already tested with ctype_digit($_GET['ID'])
What am I doing wrong here?
I see no point in such a function at all. You have $exec for your error "handling", that's enough.
// db connection
$conn = conn();
if(!$conn) {
$aErrors[] = 'Fout: Geen database verbinding!';
}
$q = "SELECT xusername, email FROM terra_user WHERE ID = ".(int)$_GET['ID']." LIMIT 1";
$exec = mysql_query($q) or trigger_error(mysql_error());
// error check
if(!$exec))
{
$aErrors[] = 'Fout: Geen database verbinding!';
}
else
{
$aRow = mysql_fetch_assoc($exec);
$uitgever = $aRow['username'];
$uitgever_email = $aRow['email'];
echo'Xteeeeeest!';
}
Though I see no point in collecting errors into array. if it's critical error, no need to wait for the other - only one is enough. if it's not a critical error - why disturb a user with it?