The following 2 queries are the result of an echo in php:
UPDATE glymping_userdata
SET current_location_gps = '51.9171115;4.484812'
WHERE id = 1
and
UPDATE glymping_user_has_appointments
SET status = 'enroute',
start_location_gps = '51.9171115;4.484812'
WHERE userId = 1
AND appointmentId = 47
Both queries work when entered manually in the database and all fields are filled correctly. When I let the php file run the queries, the queries are like shown above, but the "start_location_gps" and the "current_location_gps" are empty.
The values in the queries are strings and the database fields are a varchar(30). Yet the fields in the database are empty.
The location value is received from a post method.
Does anyone knows what I am forgetting or doing wrong?
EDIT:
php example
public function SendQuery($query)
{
$results = $this->mysqli->query($query);
return $results;
}
public function UpdateUserLocation($currentLocationGps)
{
$query = "UPDATE ".DB_PREFIX."userdata
SET current_location_gps = '{$currentLocationGps}'
WHERE id = ".$this->userId;
//echo $query;
$this->db->SendQuery($query);
}
Your current code doesn't check the return value of mysqli_query; the query might fail "silently". It could also be that the query does not affect any records in the database becaue of wrong values in the WHERE clause.
Try it with
if ( !$this->db->SendQuery($query) ) {
// query failed: syntax error, connection lost, access denied,duplicate entries, ...
trigger_error($this->mysqli->error);
}
else {
if ( 0 < $this->mysqli->affected_rows ) {
// WHERE clause doesn't match any record, no values changed, ...
trigger_error('no rows affected');
}
}
Your query might also be prone to sql injections, please check http://php.net/manual/en/security.database.sql-injection.php
Related
I'm using the SQL Server drivers for PHP to access a SQL Server database and I have a problem to update some data using sqlsrv_prpare and sqlsrv_execute functions.
I'm running two queries:
In the first query I'm retrieving some binary data (In SQL Server Management Studio, this query takes about 15 minutes to getting completed);
Then, for each row returned by the first query execution I'm trying to Update some data on the database.
Here's how my code looks like:
$query1 = "SELECT tgt.id, src.file, src.field1 from [Table1] tgt inner join [Table2] src on tgt.id = src.id order by tgt.id";
$query2 = "UPDATE [Table1] SET field1 = ? WHERE id = ?";
$getFiles = sqlsrv_query($con, $query1); //$con is the connection with the database, received by parameter
while($row = sqlsrv_fetch_array($getFiles, SQLSRV_FETCH_BOTH)) {
/* Some code here */
$file = $row[1];
$value = $row[2];
try {
if(!is_null($file)) {
$stmt = sqlsrv_prepare($con, $query2, array(&$value, &$row[0]));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute( $stmt );
}
} catch (Exception $e) {
error_log("\nError: " . $e->getMessage());
}
} //end while
sqlsrv_free_stmt($getFiles);
sqlsrv_close($con);
The problem is that the code inside the loop works fine to the first row, but on the second the update query isn't executed. The sqlsrv_prepare returns the value 1, but the sqlsrv_execute doesn't returns anything.
I'm thinking that the problem could be related to the first query execution time, but I don't know how to check this, considering that no error log is generated, the script just keeps executing forever.
EDIT: Actually, the example was simplified. The values that will be updated on tgt table are calculated using some data that are in src table and other application data. That's the reason why I use the loop, for each row returned by query1 specific values are calculated and used on query2. I already checked that these values are correctly calculated, this is why I thought it's better to simplify the example.
To solve this problem I have to ran the queries separately:
First I ran the query1, made the computation of the data that I needed to update the tgt table and stored them in an array;
Then, using the data stored in array, I ran the query2.
No other changes were needed.
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 ...");
I am trying to query a database to check if a user owns an item or not. Suppose the $username is bob and the $databaseVar is greenJacket. The value of green jacket in the database cell is either a 1 for owns or 0 for doesn't own. However, when I call the last line, return $result->$databaseVar, it always will return "greenJacket", the name of the database variable. This is bad because what I wanted what the value of the database variable. I have tried many things and can't figure it out. Any help?
public function checkIfItemOwned($username, $databaseVar)
{
$query = $this->connection->query("SELECT '$databaseVar' FROM items WHERE name='$username';");
if ($result = $query->fetch_object())
{
return $result->$databaseVar;
}
else
{
return false;
}
}
The correct SQL syntax should be: (note `` and '' symbols)
SELECT `$databaseVar` FROM items WHERE name='$username';
Otherwise, you just select the string value of $databaseVar.
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.
This code works and enters all of the correct information into the database but the error check returns an error. I could remove the error check but I'm afraid of creating some nightmare that comes back to haunt me later or that I'm missing a fundamental issue:
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
$categoryresult = mysql_fetch_array($sql5a);
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT INTO lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql5b) ) {
echo('sql5b updated successfully<br>');
} else {
echo('Error: sql5b not updated<br>'.mysql_error() );
}
if ( #mysql_query($sql6b) ) {
echo('sql6b updated successfully<br>');
} else {
echo('Error: sql6b not updated<br>'.mysql_error() );
}
The output is: "Error: sql5b not updated
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Resource id #7' at line 1"
"sql6b updated successfully"
When I check the database all entries are correct. If sql5a didn't work, sql6b couldn't work, hence my confusion over the error.
A sample Category would be: Travel/Leisure
The category was originally created from a form response:
$category = htmlentities($fbdetail['category'], ENT_QUOTES);
and entered into the database successfully. An id number was assigned using AUTO_INCREMENT.
You assign query to variable $sql5a, but call #mysql_query($sql5b).
$sql5b doesn't exist (at least in this sample). Same with $sql6a...
You can use INSERT syntax without VALUES, but you need to ommit INTO keyword.
$sql5a = mysql_query("SELECT id FROM categories WHERE category='$category'");
if ( $res5a = #mysql_query($sql5a) ) { // first execute query and store resource in variable
echo('sql5a selected successfully<br>');
} else {
echo('Error: sql5a failed<br>'.mysql_error() );
}
$categoryresult = mysql_fetch_array($res5a); // fetch array passing the RESOURCE var, NOT query string
$oldcategoryid = $categoryresult['id'];
$sql6a = "INSERT lookupcategory SET
fbid='$fbid2',
categoryid='$oldcategoryid'";
if ( #mysql_query($sql6a) ) {
echo('sql6a inserted successfully<br>');
} else {
echo('Error: sql6a failed<br>'.mysql_error() );
}
I don't know where you get $fbid2 or $category from, since it's not in this piece of code.
The syntax for the insert is :
INSERT INTO table(col1, col2 ...) VALUES(val1, val2 ...)
In your specific case:
$sql6a = "INSERT INTO table(fbid, categoryid) VALUES('{$fbid2}','{$oldcategoryid}')"