i made a lot of research around here and Google but i cannot find an answer to this problem.
I update a field in a MySQL database with following code:
public function registerPubKey() {
$stmt = $this->cn->prepare('UPDATE sb_user SET pubkey= ? WHERE email= ?');
$exres = $stmt->execute(array($this->info["pubkey"], $this->info["email"]));
if ($exres == false) {
$resultArray["result"] = "Error registering public key";
echo json_encode($resultArray);
exit;
}
$resultArray["result"] = "success";
echo json_encode($resultArray);
}
I'm sure that all works except that the field in the database is empty. I dumped the private variable $info and it contains the pubkey (pubkey is a base64 string).
I noticed that if I change the update query with an INSERT, the value is inserted correctly!
It's likely because you're trying to UPDATE non existent rows. Try adding a ON DUPLICATE KEY before. See INSERT ... ON DUPLICATE KEY UPDATE Syntax. UPDATE returns nothing if the row does not exist.
I ran into a similar issue and validated that:
the row existed, and
the execute parameters were valid and correct
The PDO::errorInfo() function can provide insight into what's actually happening to cause the update to fail:
if (! $stmt->execute($params) ) {
$resultArray["result"] = print_r($stmt->errorInfo(), true);
}
In my case, I got the message The user specified as a definer ('user'#'172.20.%.%') does not exist. Since this was a database snapshot restored to a different subnet, the error message makes sense and the user in-fact did not exist.
Related
Here is the database and PHP information:
Database vendor and version : 10.2.32-MariaDB
PHP Version : PHP 7.3
I am running into an issue when trying to retrieve the last inserted id to use in another insert statement using PHP PDO and MariaDB...
Sorry for the vague pseudo-code below but trying to mask proprietary data:
try {
include_once $pdo connection stuff here;
$pdo->beginTransaction();
$sql = 'AN INSERT STATEMENT HERE';
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':some_value', $some_value);
$stmt->bindValue(':another_one', $another_one);
$stmt->bindValue(':additional_value', $additional_value);
$stmt->execute();
// have tried to call $pdo->commit(): here to no avail.
//should get the last inserted id here on the AUTO_INCREMENT column in the target table from above prepared statement
// the AI column is not included in the insert statement above nor any value specified in the VALUES clause so should
// set to the next available value (and does so according to peeking at row over in phpMyAdmin).
$last_insert_id = $pdo->lastInsertId();
// don't really want to commit the above insert here just yet in case something goes wrong below and can rollback
// a file could be uploaded but it's not mandatory
if (!empty($_FILES['some_file'])) { // file has been attached.
// some file operations here
// some file operations here
// some file operations here
// some file operations here
$extensions = array("extension I am expecting");
if (in_array($file_ext, $extensions) === false) {
//Uh-oh not the correct extension so rolling back
$pdo->rollback();
die('message here...');
} else {
// file type is ok so proceeding
// if the file already exists, get rid of it so we don't have 2 copies on the server
if (file_exists($file_dir.$file_name)) {
unlink($file_dir.$file_name);
}
// storing the attached file in designated directory
move_uploaded_file($file_tmp, $file_dir.$file_name);
// going to parse the file...
$xml = simplexml_load_file('xml file to parse');
// have tried to call $pdo->commit(): here to no avail.
foreach ($xml->children() as $row) {
foreach ($row as $obj) {
if (some checking things with the obj here yada yada yada) {
$insert_sql = "INSERT INTO another table(columns.....) //there is no AUTO_INCREMENT column attribute on any column in this table just FYI
VALUES(column values...)";
$stmt = $pdo->prepare($insert_sql);
// want the AI value here from the very first insert above but it's always zero (0)
$stmt->bindValue(':last_insert_id', intval($last_insert_id), PDO::PARAM_INT);
$stmt->bindValue(':some_column', strval($some_column));
$stmt->bindValue(':another_one', strval($another_one));
$stmt->execute();
}
}
}
// all is good so committing the first insert
$pdo->commit();
}
} else {
// the file was not uploaded and it is not mandatory so committing the first insert here and the second insert never happens
$pdo->commit();
}
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollback();
}
throw $e;
echo 'An error occurred.';
echo 'Database Error '. $e->getMessage(). ' in '. $e->getFile().
': '. $e->getLine();
}
}
My goal is that the first insert always gets inserted (should nothing fail in it). The second insert is optional depending if a file is attached.
If the file is attached and all the file operations are good, then I'll insert some values in another table and use the auto_increment value from the first insert in this second table ( the idea is as a foreign key).
But for whatever reason, the value inserted is always zero (0).
When the code executes successfully both table inserts complete (granted a file is present and the second insert even fires)...
The row in the first table is created and 1 or more rows in the second insert's table are created but they have a value of 0 in the designated column, where I would expect them to contain the AI value from the first insert...
I've tried to call $pdo->commit() in several other places that "make sense" to me thinking that the first insert must be committed for an AI value to even exist on that table but no luck with any of them...
I even tried this I saw in another Stackoverflow post as a test to make sure PDO isn't doing anything wonky, but PDO is fine...
$conn = new PDO(connection info here);
$conn->exec('CREATE TABLE testIncrement ' .
'(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50))');
$sth = $conn->prepare('INSERT INTO testIncrement (name) VALUES (:name)');
$sth->execute([':name' => 'foo']);
var_dump($conn->lastInsertId());
And the above does return: string(1) "1"
So I think PDO is ok (granted the above was not wrapped in a transaction and I haven't tried that yet)
Hope I have provided enough clear details...
Does anyone know why I am getting 0 and not the last insert id?
Any help is greatly appreciated and thank you!
You need to check the result of $stmt->execute. Read the docs on PDOStatement::execute and you'll see that it returns a boolean value:
Returns TRUE on success or FALSE on failure.
Then read the docs on PDOStatement::errorInfo. Check this if execute returns FALSE.
$stmt->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $stmt->errorInfo();
print_r($arr);
EDIT: it's not generally a good idea to output errors to the screen, I did so in this case for convenience. A better approach would be to write a log file:
$arr = $stmt->errorInfo();
file_put_contents("/path/to/file.log", print_r($arr, TRUE));
I am trying to write a value to a database. Everything seems to be fine except one value is mysteriously incorrect. I just can't figure this out.
Using codeigniter here is my controller:
$sample_id = $this->input->post('sample_id');
$culture_id = $this->input->post('culture_id');
$sample_name = $this->vial_model->get_name($culture_id);
$box_id = $this->input->post('boxid');
$db_data['boxid'] = $box_id;
$db_data['taskid'] = $sample_id;
$db_data['projectid'] = $culture_id;
$vial_id = $this->vial_model->create($db_data);
$vial_link = '<a href="'.base_url('freezer_vial/view/'.$culture_id.'/'.$sample_id.'/'.$vial_id).'" >'.$sample_name.'</a>';
Lets imagine that the value for $sample_id is 158 (or any number really) and that I can echo this value to the view to confirm.
The anchor link that is output to the view is as expected and contains 158. However, the value for $db_data['taskid'] is always 127 and is inserted into the database as this. I have no idea why. Everything else works fine.
Here is the model:
public function create($data)
{
$insert = $this->db->insert('vial', $data);
if($insert)
return $this->db->insert_id();
else
return false;
}
The column in your database table holding the sample id value might have been defined as a tinyint. See also https://stackoverflow.com/a/16684301/282073.
You might want to alter the column type to ensure no data is altered for each new insertion or update. Instances can be found in another answer https://stackoverflow.com/a/13772308/282073
Official documentation to alter tables can be read from
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
I am developing a user/login system, wherein I have a small php function below that updates the user values in a DB when certain condition is met (i.e. when username and password matches). However, nothing seems to happen on the login page. I am using Ubuntu and on the terminal it shows that the variable $pk_user is empty. The problem is that I want to print the values of pk_user but echo, print_r, var_dump nothing prints anything on the browser. I have CSS styling, would that be the reason? The function is:
/* updateUserField - Updates a field, specified by the field parameter,
in the user's row of the database, given the pk_user */
public function updateUserField($userkey, $field, $value)
{
$q = "UPDATE users SET ".$field." = '$value' WHERE pk_user = '$userkey'";
pg_query($this->link,$q);
if(pg_last_error($this->link)) {
return -1;
}
return 1;
}
and the error message on command line is:
ERROR: invalid input syntax for
integer: "" at character 82 STATEMENT:
UPDATE users SET usr_userid =
'9bc44a3b3b0b911f7f932f06ab7d7b5c'
WHERE pk_user = ''
Of course I connect to DB with pg_connect and that part is working okay.
You're not supplying an integer as the $userkey variable when you call the function. Therefore, the query is failing. Check your code where you actually call the function to determine why an integer isn't being passed.
I'm having trouble finding a simple method for handling database errors in CI. For instance, I can't insert duplicate entries in my database table. If I try to, I get a 1062 database error.
The most common solution suggested is to check if the entry already exists and use
$query->num_rows() > 0
in a if-statement to prevent an error. That method seems redundant to me because I'm performing an extra query. Ideally I want to check if an error occurs in my main query or if a row is affected.
I found the following functions that may help
$this->db->affected_rows()
$this->db->_error_message()
however I'm not sure how to use them.
I tried in my Model:
$this->db->insert('subscription', $data);
return $this->db->affected_rows();
To my understanding that should return the number of effected rows. Then in my controller I added:
$affected = $this->Subscribe_model->subscribe($data);
if ($affected < 1)
{
//display error message in view
}
else
{
$this->Subscribe_model->subscribe($data); //perform query
}
Unfortunately the script stops in the model at $this->db->insert('subscription', $data); if an error occurs and displays the entire database error.
I do not know if this works for $this->db->insert();, but $this->db->query(); will return false if it errors so you could do something like this:
$sql = $this->db->insert_string('subscription', $data);
$sql = $this->db->query($sql)
if(!$sql){
//Do your error handling here
} else {
//query ran successfully
}
Try using #$this->db->insert('subscription', $data);, #, in PHP means "suppress warning".
As an alternate -- if you know that data is safe, or you're willing to use $this->db->insert_string, you could add, on duplicate key to the end of the query.
This should work (untested):
$this->db->simple_query( $this->db->insert_string( 'subscription', $data ) .
' ON DUPLICATE KEY ' .
$this->db->update_string(
'subscription',
$data,
/* your where clause here */ );
I am trying to implement a function that will insert a new entry in a database if a field with same name (as the one given) doesn't already exist. In particular I want to restrict duplicate usernames in a table.
The only way I could think was to run a select query and then if that doesn't return anything run the insert query. For some reason though I cant get it to work...
My db select Function
function getAllUsers($user)
{
$stmt = $this->db->stmt_init();
$stmt->prepare('SELECT username from users where username=? ');
$stmt->bind_param("s", $user);
$stmt->bind_result($username);
$stmt->execute();
$results = array();
while($stmt->fetch())
{
$results[] = array('username' => $username);
}
$stmt->close();
return $results;
}
My php code (this is in a different page)
foreach ($GLOBALS['db']->getAllUsers($_POST['username']) as $i)
{
$results = "".$i['username']."";
break;
}
if(strcmp($results, "")==0)
{
if($GLOBALS['db']->addUser($_POST['username'],$_POST['password']))
{
session_destroy();
echo "registerSucces";
}
else
{
session_destroy();
echo "registerError";
}
}
else
{
echo "userNameExists";
}
Can you see whats wrong with this???
Thanks
Mike
Still cant find how to make the above code work but just in case someone needs this: A temporary simple solution is not to compare strings at all and instead have a counter in the foreach loop and then check that upon a desired number(0 in my case)...
SQLite supports the UNIQUE constraint. Simply declare a UNIQUE index on the column and check whether an INSERT fails.
If you're using the username as the primary key in your tables, you can use the INSERT OR IGNORE command instead of checking to see if the username already exists.
If SQLite finds that an INSERT OR IGNORE command will conflict with an existing row in your table, it will simply ignore the command.
You can find out more stuff in the SQLite documentation for the INSERT command