I have the following code in a CI app :
$query = "INSERT INTO user(user_name,user_email) VALUES(?,?)";
$result = $this->db->query($query,array($userName,$email));
if ($result->num_rows()>0)
return $this->db->insert_id();
else
return null;
This yields an error ; Fatal error: Call to a member function num_rows() on a non-object in C:\xampp\htdocs\cmdline\application\models\mlogin.php on line 38
line 38 is the condition for number of rows is greater than 0 .
Now I don't get what is happening - I am using CI's documentation to check whether number of rows is greater than 0 , why does this fail ?
It's because you're doing an INSERT query. Queries that modify data return TRUE in all cases, so what you're really attempting is TRUE->num_rows(), which doesn't make any sense, causing an error.
What you actually want to check is $this->db->affected_rows(), which will tell you how many rows were inserted into the database.
Although you're not doing it in this case, it's worth noting that affected_rows() will only return the count of rows that actually changed during the query, so UPDATE queries that don't actually modify data (i.e. if the field already has the value the query is trying to set it to), then that row won't be reflected in the affected_rows() value.
From CodeIgniter's documentation.
The query() function returns a database result object when "read" type queries are run, which you can use to show your results. When "write" type queries are run it simply returns TRUE or FALSE depending on success or failure. When retrieving data you will typically assign the query to your own variable, like this:
Your query, because it's an INSERT will simply return TRUE or FALSE.
Related
I can't seem to figure out what's wrong with this PHP code:
$sql = $db->prepare("SELECT EXISTS(SELECT 1 FROM profile WHERE uid = ?)");
$p_already_exists = $sql->execute([$_SESSION['uid']]);
I'm running the sqlite3 PDO module, and it doesn't matter whether the 'uid' is in the database or not, $p_already_exists is always assigned 1. I'm expecting for it to be 0 if it's not in the database, and 1 if there is at least one record in the database.
I've double checked that echoing out $_SESSION['uid'] gives me the same value to uid (TEXT) in the database.
Does anybody know why this isn't working for me? At the end of the day I'm just after an efficient way of returning a boolean value (hence why I'm not using COUNT). Appreciate your help.
ref How to check whether SELECT EXISTS returns a value or not?
PDOStatement::execute() returns a boolean value, TRUE on success or FALSE on failure:
https://www.php.net/manual/en/pdostatement.execute.php
If you want to get the actual result returned by the SQL statement execution, rather than the status of the execution itself, you should use one of the fetch* functions, for example fetchColumn(), after calling execute().
I came across the following in some old PHP code that I have to work on. My question is, are both those Ifs required? In other words, if a result is returned it must have returned greater than zero records, right? And the converse - meaning if $result is False, can I assume that no records have been found?
$sql = "SELECT * FROM houses WHERE ownerphone=$pn";
$result = $conn->query($sql);
if ($result) {
$count = $result->num_rows;
if ($count > 0){
....Stuff happens here...
} else {
...What happens here?...
}
} else {
...Other Stuff happens here
}
Yes, both are required.
if a result is returned it must have returned greater than zero records, right?
Wrong.
If you don't get a result then you got an error and you won't have an object to read the number of results back from.
You can get zero rows back from a successful request.
if $result is False, can I assume that no records have been found?
Well, yes. Sort of. That's why the if statement stops you checking to see if there are a number of rows if the result is False.
… but not getting rows back because there was an error is different to not getting rows back because there were none to find.
No, you can't assume this. $conn->query() returns false if there's an error trying to perform a query. A SELECT query that doesn't match any rows is not an error.
Errors include incorrect syntax in the query or problems communicating with the database server.
From the docs;
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.
This means that it will bascically never return null. The first check (if ( $result ) is just to make sure all went well, and you got some kind of a response from the database. The second one is to count your rows; getting a result doesn't imply your query actually returns data, because maybe you're searching for stuff that is just not there.
I have a stored procedure in sql server.When I try to use the php function to get the results,its not working.
echo mssql_query(exec MOB_uspcommunication_details $userID,'send');
This gives result as 1 instead of resourceID.When I run the query in sql server its giving me the result.
When I change the second parameter to some other value like this,its working from PHP side.
echo mssql_query(exec MOB_uspcommunication_details $userID,'inbox');
This gives me resourceid#10 and I am getting the results.
For the first query,I am not able to understand why this happens.Please help me
From the PHP documentation:
Return Values
Returns a MS SQL result resource on success, TRUE if no rows were returned, or FALSE on error.
So that means that the first function call returns 1 to indicate there were no rows (1 == true in PHP). The second function call actually retrieves the rows from your table.
I am trying to retrieve a specific field from the first row of my query results. The following works just fine...
$result = $db->query($query);
$firstrow = $result->fetch();
$desired_field = $firstrow["field"];
My question is, can i do this in one step without storing the first row of results in a variable? Thanks in advance!
You can use fetchColumn() to return a single column from the next row in the result set. If there is only one column in the result set, do:
$desired_field = $result->fetchColumn();
If there are multiple columns in the result set, specific the numeric index of the one you want:
$desired_field = $result->fetchColumn(1);
Take notice of the warning provided in the fetchColumn() documentation:
There is no way to return another column from the same row if you use PDOStatement::fetchColumn() to retrieve data.
You can use something like $firstrow = $db->query($query)->fetch() but this is not good practice to do with functions that aren't guaranteed to return an object.
The query() function can return FALSE on error, and the dynamic call to fetch() would be a fatal error. You can't call ->fetch() on a scalar FALSE value.
For example, try the following and your script will explode:
$firstrow = $db->query("SELECT * FROM table_that_does_not_exist")->fetch();
PDO does support a mode to throw exceptions instead of returning FALSE, so in that case you are guaranteed either query()->fetch() works, or else query() will throw an exception, so you will never reach the fatal error. But you might not be using PDO's exception mode.
The answer from #GeorgeCummins points out that there's a fetchColumn() method that you can use once you have a PDOStatement object, that's a good way to get a single column. If you only need one column, name that column as the only column in your select-list, and then always use fetchColumn(0):
$oneValue = $db->query("SELECT oneColumn FROM table")->fetchColumn(0);
Otherwise if you use fetch(), this returns an array. PHP 5.4 supports array dereferencing:
$oneValue = $db->query("SELECT oneColumn FROM table")->fetch()[0];
But if you're using PHP 5.3 or earlier this is not supported. And I've never tried it with the array returned by PDOStatement so if it's actually returning an ArrayObject or something this might not work anyway.
This is guarantee to work if and only if your query is correct and there is at least one row data.
$db->query($query)->fetch(PDO::FETCH_OBJ)->field;
$RSGetID = $this->MyDBObject->Prepare("SELECT FinalID FROM clothes
WHERE ClothID=:|1 AND PriceID = :|2 LIMIT 1");
$RSGetID->Execute(2, 199);
$ClothIDRow = $RSGetID->FetchRow();
return $ClothIDRow->FinalID;
This last line gives an error, because there are no rows in the table, so it says:
"the query did not return any records"
How do I put a condition, that if the table is empty then return 0 , else return the fetched FinalID from the database table?
You're using some custom DB layer (MyDBObject?) rather than straight-up PDO - it's impossible for us to know how this behaves. There's probably a method along the lines of ->RowCount() or ->NumRows() you can call to see if you got anything back after the ->Execute() - but this is just guessing, since I can't see the DB object you're using.