I am working on a php code as shown below:
class MyDB extends SQLite3
{
function __construct()
{
$this->open('database/Podcast.db');
}
}
$db = new MyDB();
$f = $mp4_files[$_POST['id']];
$parts = pathinfo($f);
switch ($parts['extension']) {
/* Conversion of mp4 into mp3 is happening */
}
print_r($f); // Line Z
$result = $db->exec("UPDATE Podcast_Export SET Status = 'Completed' WHERE House_number = '" . $f . "'"); // Line A
if ($result == FALSE) {
echo "Error in fetch " . $db->lastErrorMsg(); // Line M
}
At Line Z, on console it prints 36031P.mp4 (When Go button is clicked from the 1st table row (from UI))
At Line Z, on console it prints hello.mp4 (When Go button is clicked from the 2nd table row(from UI))
Problem Statement:
I have a query at Line A in order to update Podcast_Export table but its not working and throwing error at Line M:
Error in fetch database is locked
At this moment, I have the following content inside Podcast_Export table:
The SQLite version which I am using is 3.27.2
From the php SQLITE3 doc
SQLite3::exec — Executes a result-less query against a given database
It returns a boolean. "Resultless" query is typcially an INSERT, UPDATE, DELETE but not a SELECT.
You might want to investigate how you could use querySingle to get the desired result.
Usually, the database is locked happened when you have an open DB process.
Check the following URL I hope to help you.
Database locked while trying to access from PHP script
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'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.
This routine used to work until we moved to a much faster debian linux server.
This is a snippet of code that reads through a csv file and inserts records into a table if another record with the same manufacturers_name dosn't exist. What is happening is the first record is inserted and when another record is found the execute function fails to find the previous inserted record and adds the record instead of updating. If I run the same routine a 2nd time without emptying the table all the records are found and only update takes place. I thought maybe the issue was speed so I tried putting sleeps in the process but it had no affect. Any ideas?
Thanks
while (($data = fgetcsv($handle, 0, chr(9),chr(0))) !== FALSE) {
****** Setup stuff here *******
$msql_data_array = array('manufacturers_name' => $data[$manufacturer_sn]);
$sql = "select count(*) as total,manufacturers_id,manufacturers_name from " . TABLE_MANUFACTURERS . " where manufacturers_name = \"" . $data[$manufacturer_sn] . "\"";
$manufacturers = $db->Execute($sql);
if ($manufacturers->fields['total'] == 0) { <<<<<<<<<<<< This always returns 0 even if the record was just added by the previous operation(s)
***** Inserts a new record ******
} else {
***** Updates the current record *******
}
]
This looks like a simple .csv import. You could replace the PHP code with a command line MySQL call, like so:
mysqlimport --fields-terminated-by '\t' db_name import.csv
Ref: http://dev.mysql.com/doc/refman/5.7/en/mysqlimport.html
I am working with a php program and want to check if a table exists. If it does exist, do nothing, if it doesn't create and populate the table. I ran across
if(mysql_query("DESCRIBE `table`")) {
// Exists
}
but this only takes action if it does exist. Would this
if(!mysql_query("DESCRIBE `table`")) {
// create and populate table
}
do what I am asking?
What you're doing won't work because the test is only testing the return value of the mysql_query() call, not the result of the query itself.
You need to query the tables with SHOW TABLES LIKE 'table' and check the number of rows returned:
$db = new mysqli(...);
$result = $db->query("SHOW TABLES LIKE 'table'");
if ($result->num_rows == 0) {
// create table
}
Note: mysql_*() is deprecated - you shouldn't use it for new code.
You'll find the MySQL reference here, and the PHP reference for mysqli here
I have a table in my database that looks like this:
|id|team_name|team_url|xml|
I have a cronjob that calls a script. In this script, I want to use my class to check if the url exists, and if it doesn't, delete the entry in the database. Something like this:
foreach row in table, if (Security::checkUrl(team_url)), delete entry. else: update xml.
How can I do something like this? I don't need help with the url verification only the mysql query and how i should go through each row and delete the rows where the url is invalid.
Thanks.
The mysql query to delete the row would be
DELETE FROM tablename WHERE team_url = '$team_url';
$team_url is the php variable which has the team_url value.
The above command will delete all rows where the team_url matches $team_url.
What you will want to do is in php loop through all the rows and check their URL.
$query = "SELECT * FROM tablename";
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
if (Security::checkUrl($row['team_url'])) {
$res = mysql_query("DELETE FROM tablename WHERE team_url = '".mysql_real_escape_string($row['team_url'])."'");
}
else {
//update xml
}
}
mysql_free_result($result);
The above code is just a sample and not to be used in production without proper sql injection cleaning / checking.
To delete a row with a given URL, prepare a query like 'DELETE FROM table WHERE team_url=?' with, e.g.,
mysqli_stmt::prepare(). Then bind the URL that you want to delete to the parameter with mysqli_stmt::bind_param(), à la bind_param("s", $dead_url). Then execute the statement using mysqli_stmt::execute().
EDIT: per strager's suggestion: the mysqli reference in the PHP manual is here: http://php.net/manual/en/book.mysqli.php. It has links to documentation for all the functions that I just mentioned.