Check if update executed in pecee-pixie - php

I am using pecee-pixie
I run:
$result = $query_builder->where("id", "=", 4)->update($data_array);
and it executes correctly. However I want to check if the query got executed and if it failed I would like to insert the data to the array. Alas the where statements are not primary keys so i cannot use ON DUPLICATE KEY statement.
How can i check if the last query was executed with a success?

I have never used the method before but this library has updateOrInsert method that might work.
You can also easily check if the query was executed by checking the affected row count
$result = $query_builder->where("id", "=", 4)->update($data_array);
$count = $result->rowCount();
if($count > 0) {
//update executed
} else {
//update failed do the insert
}

Related

Get 'Update' error using SQLite3 and PHP

I created a function that tries to UPDATE a value using a condition. If something goes wrong, it tries to do a INSERT.
The code is as follow:
if(!$result=$this->query("UPDATE collect_data_settings SET setting_value ='".$setting_value."' WHERE collect_point = '".$collect_point."' AND setting_name='".$setting_name."';"))
$result=$this->query("INSERT INTO collect_data_settings ('collect_point','setting_name','setting_value') VALUES ('".$collect_point."','".$setting_name."','".$setting_value."');");
Unfortunately, for some reason the UPDATE query never returns false even if the condition is not satisfied. Can someone help me?
Why don't you try doing a search for the collect_point (assuming this is a unique key) variable first and if it is not yet in the database you use the INSERT statement and if not you use the UPDATE statement. For example:
$db = new SQLite3('database.db')
$check = $db->query("SELECT * FROM collect_data_settings WHERE collect_point = '$collect_point'")
$check_query = $check->numRows();
if($check_query > 0) {
*Your UPDATE query*
}else {
*Your INSERT query*
}
The UPDATE statement modifies all rows that happen to match the WHERE condition. The final number does not matter; even if no row matches, all rows were checked successfully.
To find out how many rows were changed, use the changes() function:
$this->exec("UPDATE ... WHERE ...");
if ($this->changes() == 0)
$this->exec("INSERT ...");

PHP Mysqli statement returns a single row, -1 rows affected, and no error

This is so baffling I MUST be missing something simple. I have a query that checks to see if the transaction I'm inserting already exists in order to prevent duplicates. Here's the code:
function isaDupe($portableDB, $transactArray)
{
$ref = $transactArray["reference"];
$date = $transactArray["qdate"];
$time = $transactArray["time"];
//prints the query so I can run by hand to test
print "SELECT `counter` FROM transactions WHERE (`reference` = '$ref' AND `qdate` = '$date' AND `time` = '$time') ";
if ($dupeSelectStmt = $portableDB->prepare("SELECT `counter` FROM transactions WHERE (`reference` = ? AND `qdate` = ? AND `time` = ?)"))
{
$dupeSelectStmt->bind_param('sss',$ref, $date, $time);
$dupeSelectStmt->bind_result($counter);
$dupeSelectStmt->execute();
while ($dupeSelectStmt->fetch())
{
break;
}
$numRows = $portableDB->affected_rows;
if ($numRows > 0)
return TRUE;
else if ($numRows == -1)
{
print " ERROR: ";
print_r($portableDB->error);
print_r($dupeSelectStmt->error);
return FALSE;
}
else
return FALSE;
}
}
-If I run the query by hand through Workbench on the same server, I get 24 rows returned.
--this is the same if I prepare, set, and execute the statement by hand.
-affected_rows returns -1
--same if I do num_rows on the statement
-there is no error stored on the Statement or MySQLi object.
-if I put a print in the fetch() statement, it prints one row's worth of data
-if I store the fetched rows into an array and count the results, it's 1
-I've tried running it with each variable separately, same thing.
-other queries on the same server (heck, on the same MySQLi object) are working fine. SELECTS, UPDATES, and INSERTS.
The answer is I was forgetting to call mysqlistmt::store_result after mysqlistmt::execute().
Once I added $dupSelectStmt->store_result(); I was able to call $dupSelectStmt->num_rows and $portableDB->affected_rows and they both showed the 24 I knew I should be seeing.
You need you use $dupeSelectStmt->num_rows() to get the number of rows in the result set for a SELECT. You need to call either affected_rows (for INSERT, DELETE, UPDATE) or num_rows() on the mysqli_stmt object not not on the database handle ($portableDB) as you are currently doing.

How do I tell when a MySQL UPDATE was successful versus actually updated data?

How do I tell when a MySQL UPDATE was successful versus actually updated data?
Example:
TABLE
id city_name
1 Union
2 Marthasville
If I run the following:
$data = array('city_name', 'Marthasville');
//update record 2 from Marthasville to the same thing, Marthasville.
$this->db->where('id', 2);
$this->db->update('table', $data);
if($this->db->affected_rows() > 0)
{
//I need it to return TRUE when the MySQL was successful even if nothing was actually updated.
return TRUE;
}else{
return FALSE;
}
This will return TRUE every time the UPDATE statement is successful, but FALSE when no rows were actually updated.
I need it to return TRUE every time the UPDATE statement was successfully executed even if it doesn't actually change any records.
Have a look at mysql_affected_rows()
It should tell you if anything was actually updated as opposed to nothing was successfully updated resulting in a return of true.
php.net says:
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last
query failed.
You could use the following to achieve your desired results:
if($this->db->affected_rows() >= 0){ }
Then you would use mysql_query:
SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query()
returns TRUE on success or FALSE on error.
Simple like this:
$result = $this->db->update('table', $data);
if($result)
{
//without error even no row updated
} else {
}

mysql_fetch_array() timing out

I am trying to query a database, but it seems to just load for an age and not do anything. It's a simple query and shouldnt take longer than a millisecond.
while($row = mysql_fetch_array(getWallPosts($userid)))
{
}
Now when I replace this code with:
echo mysql_num_rows(getWallPosts($userid));
It just displays '1' in fact there's only one record in the DB and it's just a simple SELECT statement.
Here's the getWallPosts function:
function getWallPosts($userid, $limit = "10")
{
$result = dbquery("SELECT * FROM commentpost
WHERE userID = ".$userid."
ORDER BY commentPostID DESC LIMIT 0, ".$limit);
return $result;
}
Also, when I put the SQL string that it's executing into MySQL's query browser. It takes no time at all.
Any ideas?
You appear to be looping indefinitely because you're retrieving a new set (one record) of data each time.
$result = getWallPosts($userid);
while ($row = mysql_fetch_array($result)) {
//printf($row[0]);
}
You need to get the data once and loop through it. Your code is getting the data, running the loop and then getting the data again.
Try:
$posts = getWallPosts($userid);
while($row = mysql_fetch_array($posts))
{
//Code to execute
}
Its an infinite loop. The expression in the while always executes so it will always be true.
You're returning a new result set each time the while statement executes. You should call getWallPosts first, assign it to $results, and then loop over it.

Whats the proper way to check if mysql_query() returned any results?

I tried what seemed like the most intuitive approach
$query = "SELECT * FROM members
WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
if ($result)
{ ...
but that didn't work because mysql_query returns a true value even if 0 rows are returned.
I basically want to perform the logic in that condition only if a row is returned.
Use mysql_num_rows:
if (mysql_num_rows($result)) {
//do stuff
}
If you're checking for exactly one row:
if ($Row = mysql_fetch_object($result)) {
// do stuff
}
You can use mysql_fetch_array() instead, or whatever, but the principle is the same. If you're doing expecting 1 or more rows:
while ($Row = mysql_fetch_object($result)) {
// do stuff
}
This will loop until it runs out of rows, at which point it'll continue on.
mysql_num_rows
Retrieves the number of rows from a result set. This command is only valid for statements like SELECT or SHOW that return an actual result set.
If none match, then zero will be the return value and effectively FALSE.
$result = mysql_query($query);
if(mysql_num_rows($result))
{ //-- non-empty rows found fitting your SQL query
while($row = mysql_fetch_array($result))
{//-- loop through the rows,
//-- each time resetting an array, $row, with the values
}
}
Which is all good and fine if you only pull out of the database. If you change or delete rows from the database and want to know how many were affected by it...
To retrieve the number of rows affected by a INSERT, UPDATE, REPLACE or DELETE query, use mysql_affected_rows().
$result = mysql_query($query);
if(mysql_affected_rows())
{ //-- database has been changed
}
//-- if you want to know how many rows were affected:
echo 'Rows affected by last SQL query: ' .mysql_affected_rows();
mysql_query() will only return FALSE if the query failed. It will return TRUE even if you have no rows, but successfully queried the database.
$sql = "SELECT columns FROM table";
$results = mysql_query($sql, $conn);
$nResults = mysql_num_rows($results);
if ($nResults > 0) {
//Hurray
} else {
//Nah
}
This should work.
I used the following:
if ($result != 0 && mysql_num_rows($result)) {
If a query returns nothing it will be a boolean result and it's value will be 0.
So you check if it's a zero or not, and if not, we know there's something in there..
HOWEVER, sometimes it'll return a 1, even when there is nothing in there, so you THEN check if there are any rows and if there is a full row in there, you know for sure that a result has been returned.
What about this way:
$query = "SELECT * FROM members WHERE username = '$_CLEAN[username]'
AND password = '$_CLEAN[password]'";
$result = mysql_query($query);
$result = mysql_fetch_array($result);
//you could then define your variables like:
$username = $result['username'];
$password = $result['password'];
if ($result)
{ ...
I like it because I get to be very specific with the results returned from the mysql_query.
-Ivan Novak
well...
by definiton mysql_query:
mysql_query() returns a resource on
success, or FALSE on error.
but what you need to understand is if this function returns a value different than FALSE the query has been ran without problems (correct syntax, connect still alive,etc.) but this doesnt mean you query is returning some row.
for example
<?php
$result = mysql_query("SELECT * FROM a WHERE 1 = 0");
print_r($result); // => true
?>
so if you get FALSE you can use
mysql_errorno() and mysql_error() to know what happened..
following with this:
you can use mysql_fetch_array() to get row by row from a query
$result = mysql_query(...);
if(false !== $result)
{
//...
}

Categories