doctorbill
asked on
php insert
I have the following php page:
The code works perfectly in uploading the document but refuses to add any data to the database
Ideas please?
<?php
session_start();
echo $_SESSION['someKey'];
echo $_SESSION['documentname'];
if(!empty($_FILES)){
//database configuration
$company = $_SESSION['someKey'];
$it_docname = $_SESSION['documentname'];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'xxxxxx';
$dbName = 'inventas';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$targetDir = "uploads/";
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileLink = $_FILES['file']['link'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO documents (companyName, f_name, f_name_itdoc, d_date, f_size, f_type, f_link) VALUES('".$company."','".$fileName."','".$it_docname."','".date("Y-m-d H:i:s")."','".$fileSize."','".$fileType."','".$fileLink."')");
}
}
?>
I would add that you should also consider using PDO instead of MySQLi - it will make your life a lot easier - especially with respect to prepared statements.
Another option to debug is echo out the query to the screen and then try and run that manually in your SQL Query Editor.
We can't help you here as we don't have your schema or the data you are trying to insert - vital clues to solving the problem.
Another option to debug is echo out the query to the screen and then try and run that manually in your SQL Query Editor.
We can't help you here as we don't have your schema or the data you are trying to insert - vital clues to solving the problem.
ASKER
One thing I am not clear about:
I am using the same php version in WAMP as I used in my old xampp install
WAMP is throwing up loads of errors on each page whereas the same site on xampp with the same php version works perfectly
any ideas?
I am using the same php version in WAMP as I used in my old xampp install
WAMP is throwing up loads of errors on each page whereas the same site on xampp with the same php version works perfectly
any ideas?
1) As @gr8gonzo mentioned, you've checked the connect error + taken action.
2) Check your SQL statement (INSERT) for errors + take action also.
3) The error you attached is clear.
On line #2 in pdf_invemail.php, you're referencing a file which can't be found.
This likely relates to the include path setup you have for your WAMP setup + is different from your database error.
You'll fix this in your php.ini file + if you get stumped, best to open another question to discuss fixing this, to keep this question related to your initial SQL question.
2) Check your SQL statement (INSERT) for errors + take action also.
3) The error you attached is clear.
On line #2 in pdf_invemail.php, you're referencing a file which can't be found.
This likely relates to the include path setup you have for your WAMP setup + is different from your database error.
You'll fix this in your php.ini file + if you get stumped, best to open another question to discuss fixing this, to keep this question related to your initial SQL question.
Those errors are because PHP cannot find the files in question.
I am guessing this is due to the '/' at the front of the path. This means search from the root of the server (the server webroot). Unless you have configured your new server exactly the same with respect to paths as your old you are going to have problems.
You need to check if the requested files exist relative to the webroot of your site so whatever folder you go to when you browse to
http://yourserver or http://localhost (no other folders after the domain)
The includes/pdf folder must exist relative to that.
I am guessing this is due to the '/' at the front of the path. This means search from the root of the server (the server webroot). Unless you have configured your new server exactly the same with respect to paths as your old you are going to have problems.
You need to check if the requested files exist relative to the webroot of your site so whatever folder you go to when you browse to
http://yourserver or http://localhost (no other folders after the domain)
The includes/pdf folder must exist relative to that.
ASKER
Then you need to either
Option 1.
In the same folder as Development make sure you have
/includes/pdf
Option 2
change your require_once to
Option 3
You could also do a relative include based on where your file is located - based on the screen grab it looks like the Sites folder. (i.e remove the '/' from the front of the path)
Option 1.
In the same folder as Development make sure you have
/includes/pdf
(/Development/includes/pdf)
Option 2
change your require_once to
require_once('/Development/Inventas/Sites/includes/pdf/...');
Option 3
You could also do a relative include based on where your file is located - based on the screen grab it looks like the Sites folder. (i.e remove the '/' from the front of the path)
require_once('includes/pdf/...');
ASKER
Update:
I managed to solve the pdf issue by switching to DomPD8:
I managed to solve the pdf issue by switching to DomPD8:
<?php
use Dompdf\Dompdf;
use Dompdf\Options;
require_once("includes/DomPDF8/dompdf/autoload.inc.php");
//$companyname = $row_emOID['CustName'];
$filename = time();
$html = "";
ob_start();
//include('orders_find_visit_print_custom_status_noforms_nocosts_PDF.php');
include('searchProRepPDF.php');
//$filename2 = $row_emOID['CustName'];
//$filename3 = $row_emOID['Date'];
$filename2 = "Name1";
$filename3 = "Name2";
$html = ob_get_contents();
ob_end_clean();
$dompdf = new DOMPDF();
$dompdf->load_html($html);
//$dompdf = set_paper("a4");
$dompdf->render();
$dompdf->stream("proactivity-$filename2-$filename3-$filename.pdf");
?>
ASKER
The thing is - I still have the original issue:
The following code works perfectly in that it uploads the file to the correct folder in the host but refuses to enter the data into the database
I know it is difficult to see where the code is going wrong when you don't have anything else to visualise but can you explain the steps to carry out the suggestions made above and also where the code may be failing:
1. "echo out the query to the screen and then try and run that manually in your SQL Query Editor"
2. "Check the result of $conn->query(...) to see if it equals false. If it does, echo out the value of $conn->error"
3. Suggest a PDO statement
The strange thing is the exact same code works in the same version of PHP and same set of site files in xampp using the MariaDB - uploading a file and inserting into the database
I tried the MariaDB in the WAMP as opposed to the MySQL and have the same problem
The following code works perfectly in that it uploads the file to the correct folder in the host but refuses to enter the data into the database
I know it is difficult to see where the code is going wrong when you don't have anything else to visualise but can you explain the steps to carry out the suggestions made above and also where the code may be failing:
1. "echo out the query to the screen and then try and run that manually in your SQL Query Editor"
2. "Check the result of $conn->query(...) to see if it equals false. If it does, echo out the value of $conn->error"
3. Suggest a PDO statement
The strange thing is the exact same code works in the same version of PHP and same set of site files in xampp using the MariaDB - uploading a file and inserting into the database
I tried the MariaDB in the WAMP as opposed to the MySQL and have the same problem
<?php
session_start();
echo $_SESSION['someKey'];
echo $_SESSION['documentname'];
if(!empty($_FILES)){
//database configuration
$company = $_SESSION['someKey'];
$it_docname = $_SESSION['documentname'];
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'xxxxxxx';
$dbName = 'inventas';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$targetDir = "uploads/";
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fileLink = $_FILES['file']['link'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO documents (companyName, f_name, f_name_itdoc, d_date, f_size, f_type, f_link) VALUES('".$company."','".$fileName."','".$it_docname."','".date("Y-m-d H:i:s")."','".$fileSize."','".$fileType."','".$fileLink."')");
}
}
?>
Can you try this
Note: I am using the code below as it is what you have used. Typically
a) I would prefer PDO [See code at bottom of post]
b) I would definitely use a prepared statement with bound parameters rather than string insertion as you have it below
c) I prefer to letting the server insert dates with CURRENT_TIMESTAMP (current_timestamp()) over inserting the date from the client.
1. If there is an error in the file - fix it / post it
2. If no error then copy the query from the file and paste into a query editor and run it against the database.
Report back here
NB: The code above is not tested - I have checked it as best I can but it may not function as intended. If it does not produce the log file in the folder where your entry script resides then check the code and amend to fix any errors or suit your environment.
Here is what your code could look like as a PDO implementation
Stay DRY - separate common code into their own scripts
[common.php]
Note: I am using the code below as it is what you have used. Typically
a) I would prefer PDO [See code at bottom of post]
b) I would definitely use a prepared statement with bound parameters rather than string insertion as you have it below
c) I prefer to letting the server insert dates with CURRENT_TIMESTAMP (current_timestamp()) over inserting the date from the client.
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
$date=date("Y-m-d H:i:s");
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
'{$company}',
'{$fileName}',
'{$it_docname}',
'{$date}',
'{$fileSize}',
'{$fileType}',
'{$fileLink}'
)
EOT;
file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
//insert file information into db table
if (!$conn->query($query)) {
file_put_contents('DEBUG.LOG', "Error message: {$mysqli->error)\n", FILE_APPEND);
}
}
Run the code again and do the following1. If there is an error in the file - fix it / post it
2. If no error then copy the query from the file and paste into a query editor and run it against the database.
Report back here
NB: The code above is not tested - I have checked it as best I can but it may not function as intended. If it does not produce the log file in the folder where your entry script resides then check the code and amend to fix any errors or suit your environment.
Here is what your code could look like as a PDO implementation
Stay DRY - separate common code into their own scripts
[common.php]
<?php
session_start();
// Other common functions / defines / variables
[dbconnection.php]<php
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = 'xxxxxxx';
$dbName = 'inventas';
$dsn = 'mysql:dbname={$dbName};host={$dbHost}';
try {
$conn = new PDO($dsn, $dbUsername, $dbPassword);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Main script<?php
require_once('common.php');
require_once('dbconnection.php');
// IMPORTANT: Validate your SESSION variables here!!!
if(!empty($_FILES)){
// The following might need to go to a config file;
$targetDir = "uploads/";
$targetFile = $targetDir . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
// SETUP YOUR NAMED QUERY PARAMETERS.
// NAMED PARAMETERS GIVE YOU FAR MORE FLEXIBILITY IN TERMS OF REPEATED
// VARIABLES AND ORDER OF PARAMETERS
$params = [
'company' => $_SESSION['someKey'],
'fileNme' => $_FILES['file']['name'],
'it_docname' => $_SESSION['documentname'],
'date' => $date=date("Y-m-d H:i:s"), // Potentially move to DB as CURRENT_TIMESTAM
'fileSize' => $_FILES['file']['size'],
'fileType' => $_FILES['file']['type'],
'fileLink' => $_FILES['file']['link']
];
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
$stmt = $conn->prepare($query);
if (!$stmt->execute($params)) {
// If error logging is setup then use
// error_log(....)
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND);
}
}
}
As before - this is untested code, you might need to tweak if there are typos.
ASKER
I have now tried all of the above
Again, the file is uploaded but nothing is added to the database
The same file works in xampp (as mentioned above) but not in wamp
I have no idea what is stopping the database entry
There must be some difference in the wamp server config
Again, the file is uploaded but nothing is added to the database
The same file works in xampp (as mentioned above) but not in wamp
I have no idea what is stopping the database entry
There must be some difference in the wamp server config
What was the output from the script?
Was the DEBUG.LOG file created?
If so what were the contents of the file?
Did you copy the output query in DEBUG.LOG and try that in a Query editor?
If so what was the result?
The previous post provided several avenues of exploration - which you have not reported back on.
Was the DEBUG.LOG file created?
If so what were the contents of the file?
Did you copy the output query in DEBUG.LOG and try that in a Query editor?
If so what was the result?
The previous post provided several avenues of exploration - which you have not reported back on.
ASKER
Where would the debug .log files be?
What query editor would you suggest?
What query editor would you suggest?
ASKER
I could use visual code studio or php storm
Any other suggestions?
Any other suggestions?
The code I gave you creates the file DEBUG.LOG (look at the file_put_contents statements) (Refer line 23 and 27 of the first source listing)
The whole point of the exercise was to dump what the script was doing.
This would have been written to the same folder that the landing script is in - in otherwords the script that you called to do the insert - it will be in the same folder.
What we are trying to do here is discover if
a) There is an error in your query structure
b) If the query itself is correct with respect to the schema
We don't have access to your schema so we have to do this the long way - which is for you to dump debug data and then use it on your side.
If you implemented the PDO code then simply add line 23 from the first listing
Execute the code and get us the contents of the DEBUG.LOG file.
The whole point of the exercise was to dump what the script was doing.
This would have been written to the same folder that the landing script is in - in otherwords the script that you called to do the insert - it will be in the same folder.
What we are trying to do here is discover if
a) There is an error in your query structure
b) If the query itself is correct with respect to the schema
We don't have access to your schema so we have to do this the long way - which is for you to dump debug data and then use it on your side.
If you implemented the PDO code then simply add line 23 from the first listing
file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
To after line 44 of the second listing...
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
// ADD THIS
file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
$stmt = $conn->prepare($query);
...
Execute the code and get us the contents of the DEBUG.LOG file.
Query editor - how are you interacting with your Database at the moment?
Options are
PHPMyAdmin
Mysql WorkBench
Heidi
SQLYog
Options are
PHPMyAdmin
Mysql WorkBench
Heidi
SQLYog
ASKER
I will re-run the upload to see if I can generate the debug file - it is not in the folder at present
ASKER
This is the file I am running:
<php
require_once('common.php');
require_once('dbconnection.php');
// IMPORTANT: Validate your SESSION variables here!!!
if(!empty($_FILES)){
// The following might need to go to a config file;
$targetDir = "uploads/";
$targetFile = $targetDir . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
// SETUP YOUR NAMED QUERY PARAMETERS.
// NAMED PARAMETERS GIVE YOU FAR MORE FLEXIBILITY IN TERMS OF REPEATED
// VARIABLES AND ORDER OF PARAMETERS
$params = [
'company' => $_SESSION['someKey'],
'fileNme' => $_FILES['file']['name'],
'it_docname' => $_SESSION['documentname'],
'date' => $date=date("Y-m-d H:i:s"), // Potentially move to DB as CURRENT_TIMESTAM
'fileSize' => $_FILES['file']['size'],
'fileType' => $_FILES['file']['type'],
'fileLink' => $_FILES['file']['link']
];
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
$stmt = $conn->prepare($query);
if (!$stmt->execute($params)) {
// If error logging is setup then use
// error_log(....)
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND);
}
}
}
?>
You need to add the line after line 44 as per my last post.
ASKER
ok - will try it
ASKER
I ran this but no debug file was produced:
<php
require_once('common.php');
require_once('dbconnection.php');
// IMPORTANT: Validate your SESSION variables here!!!
if(!empty($_FILES)){
// The following might need to go to a config file;
$targetDir = "uploads/";
$targetFile = $targetDir . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
// SETUP YOUR NAMED QUERY PARAMETERS.
// NAMED PARAMETERS GIVE YOU FAR MORE FLEXIBILITY IN TERMS OF REPEATED
// VARIABLES AND ORDER OF PARAMETERS
$params = [
'company' => $_SESSION['someKey'],
'fileNme' => $_FILES['file']['name'],
'it_docname' => $_SESSION['documentname'],
'date' => $date=date("Y-m-d H:i:s"), // Potentially move to DB as CURRENT_TIMESTAM
'fileSize' => $_FILES['file']['size'],
'fileType' => $_FILES['file']['type'],
'fileLink' => $_FILES['file']['link']
];
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
// ADD THIS
file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
$stmt = $conn->prepare($query);
$stmt = $conn->prepare($query);
if (!$stmt->execute($params)) {
// If error logging is setup then use
// error_log(....)
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND);
}
}
}
?>
At the beginning of your code, change <php to <?php
ASKER
Ooops!!
Thanks - typo
Thanks - typo
ASKER
Results of the debug file:
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
Ok we have a debug file - now change line 46
The idea is you want to take the query, substitute the parameter data and try and run that against your database. If unsure - post debug.log here and we can take it from ther.e
file_put_contents('DEBUG.LOG',print_r(['query' => $query, 'params' => $params], true) . "\n", FILE_APPEND);
This should dump the query and the parameters sent to the query in the fileThe idea is you want to take the query, substitute the parameter data and try and run that against your database. If unsure - post debug.log here and we can take it from ther.e
ASKER
Could this be an issue with SESSIONS:
Result:
Result:
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
Array
(
[query] => INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
[params] => Array
(
[company] =>
[fileNme] => ABCabcd.txt
[it_docname] =>
[date] => 2021-08-18 14:57:07
[fileSize] => 12
[fileType] => text/plain
[fileLink] =>
)
)
I am seeing some blanks in the data - not sure if this is an issue - it will depend on your Database.
Here is the active query replacing named parameters with values. Please run this against your database and let us know if the data is inserted - and if not what the error is.
Here is the active query replacing named parameters with values. Please run this against your database and let us know if the data is inserted - and if not what the error is.
INSERT INTO documents ( companyName,f_name,f_name_itdoc,d_date,f_size,f_type,f_link)
VALUES('','ABCabcd.txt','','2021-08-18 14:57:07','12','text/plain','')
Regarding your question on Sessions - given that two of the missing values are supposed to come from the SESSION then this is a very likely cause.
Where are these values being set? Are you certain you have session_start() (common.php) in the script that is setting these values?
Where are these values being set? Are you certain you have session_start() (common.php) in the script that is setting these values?
ASKER
I tried this:
I checked the SESSIONS on the relevant pages and they have the session_start()
INSERT INTO documents ( companyName,f_name,f_name_itdoc,d_date,f_size,f_type,f_link)
VALUES('','ABCabcd.txt','','2021-08-18 14:57:07','12','text/plain','')
No change - nothing added to the databaseI checked the SESSIONS on the relevant pages and they have the session_start()
No change - nothing added to the databaseWell that is your problem. If the query does nothing when you run it manually there is no way it is going to work from script.
You need to get that query working - find out why it is not - and work backwards from there.For starters manually fill in the blank values for the query and run it manually again - does this work. If so then the problem is the SESSION variables being blank - if not then you need to give us more information about your database and in particular the table you are trying to insert into.
Then you need to investigate why your SESSION values are not coming through.
Unfortunately these are not things we can help you with - you will need to check them.
For the sessions - if you want us to help you are going to need to explain how you are using sessions and in particular the flow around the two session variables you are using in the query.
Just to recap:
1. Are you using PDO at this point, or mysqli?
2. If you're using PDO, then do:
Note that in the first section, it's $conn->errorInfo(), and in the second section it's $stmt->errorInfo().
The reason for this is because prepare() is a method of the PDO connection, so if it fails and you get a false in return, then to see the reason WHY it failed, you have to look at the $conn connection object for the error.
If prepare() succeeds and gives you a statement object, but it fails to execute() for some reason, then you want to look at the error on the statement object.
Also, you mentioned that it failed in MariaDB but not in MySQL, and works if you run it manually. While it's rare, you might want to double-check to make sure that the credentials you're using are permitted to read and write to that table in your MariaDB instance. Both databases allow you to be very granular when it comes to access control, so you might be able to use some credentials to connect and maybe even read data from one table but not another, or maybe read but not write to a table. If the query fails and logs an error, then it should tell you if there's a permissions problem like this. Or you might have an account that gives you full permissions if you connect from one IP address but limited permissions if you connect from a different IP.
And if there is a permissions problem, I would suggest a tool like HeidiSQL to give you a visual display of all the user accounts on the system (after connecting, there's a User Manager tool that will do this).
1. Are you using PDO at this point, or mysqli?
2. If you're using PDO, then do:
$stmt = $conn->prepare($query);
if($stmt === false)
{
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $conn->errorInfo()]) . "\n", FILE_APPEND); }
}
elseif (!$stmt->execute($params))
{
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND); }
{
else
{
echo "Query successful!";
}
Note that in the first section, it's $conn->errorInfo(), and in the second section it's $stmt->errorInfo().
The reason for this is because prepare() is a method of the PDO connection, so if it fails and you get a false in return, then to see the reason WHY it failed, you have to look at the $conn connection object for the error.
If prepare() succeeds and gives you a statement object, but it fails to execute() for some reason, then you want to look at the error on the statement object.
Also, you mentioned that it failed in MariaDB but not in MySQL, and works if you run it manually. While it's rare, you might want to double-check to make sure that the credentials you're using are permitted to read and write to that table in your MariaDB instance. Both databases allow you to be very granular when it comes to access control, so you might be able to use some credentials to connect and maybe even read data from one table but not another, or maybe read but not write to a table. If the query fails and logs an error, then it should tell you if there's a permissions problem like this. Or you might have an account that gives you full permissions if you connect from one IP address but limited permissions if you connect from a different IP.
And if there is a permissions problem, I would suggest a tool like HeidiSQL to give you a visual display of all the user accounts on the system (after connecting, there's a User Manager tool that will do this).
ASKER
Manually filling in the blank values did not change anything
I also tried changing the database fields which are not getting data to NULL - again no change
Would it help to attach the database (very small file)?
I also tried changing the database fields which are not getting data to NULL - again no change
Would it help to attach the database (very small file)?
ASKER
gr8gonzo:
The query works in MariaDB in xampp not - the files are being uploaded and the database is being filled in
I have tried it in WAMP in both MariaDB and MySQL - the same issue happens in both
ALL:
Could there be some config setting in WAMP causing this?
The query works in MariaDB in xampp not - the files are being uploaded and the database is being filled in
I have tried it in WAMP in both MariaDB and MySQL - the same issue happens in both
ALL:
Could there be some config setting in WAMP causing this?
That needs a bit of clarification. Let's say these are environments (just for the sake of example)::
Environment #1: "WAMP 1"
Web Server: Apache, running on localhost
Database: MariaDB, running on localhost
Result: File upload fails, database record inserts OK
Environment #2: "WAMP 2"
Web Server: Apache, running on localhost
Database: MariaDB, running on remote server
Result: File upload fails, database record fails
Environment #3: "XAMPP"
Web Server: Apache, running on localhost
Database: MySQL, running on localhost
Result: File uploads OK, database record fails
Environment #4: "LAMP"
Web Server: Apache, running on remote server
Database: MariaDB, running on remote server
Result: File uploads OK, database record inserts OK
Can you provide a similar listing of the actual combinations/environments and what fails or succeeds? Also, can you confirm whether the PHP database connection code uses the word "localhost" in each environment, or does the connection configuration change a bit (e.g. in your development environment, maybe you changed the PHP code to connect to a remote IP)?
Environment #1: "WAMP 1"
Web Server: Apache, running on localhost
Database: MariaDB, running on localhost
Result: File upload fails, database record inserts OK
Environment #2: "WAMP 2"
Web Server: Apache, running on localhost
Database: MariaDB, running on remote server
Result: File upload fails, database record fails
Environment #3: "XAMPP"
Web Server: Apache, running on localhost
Database: MySQL, running on localhost
Result: File uploads OK, database record fails
Environment #4: "LAMP"
Web Server: Apache, running on remote server
Database: MariaDB, running on remote server
Result: File uploads OK, database record inserts OK
Can you provide a similar listing of the actual combinations/environments and what fails or succeeds? Also, can you confirm whether the PHP database connection code uses the word "localhost" in each environment, or does the connection configuration change a bit (e.g. in your development environment, maybe you changed the PHP code to connect to a remote IP)?
In addition to what Gr8gozon said - I think you need to pay some attention to the database part. WAMP is just a collection of application - the only relevant one for now is MySQL / Maria.
You have reported that when you run the query manually against the database it does not work. This is the part I am not clear on - "does not work" can mean a few things
1. The query ran without errors but no record was inserted - this would not make sense
2. The query ran with errors - again does not make sense as you would have posted them here
I don't understand how running the query in the post above cannot work without throwing an error.
There is a piece you are not telling us.
You have reported that when you run the query manually against the database it does not work. This is the part I am not clear on - "does not work" can mean a few things
1. The query ran without errors but no record was inserted - this would not make sense
2. The query ran with errors - again does not make sense as you would have posted them here
I don't understand how running the query in the post above cannot work without throwing an error.
There is a piece you are not telling us.
ASKER
That is exactly the problem
The query runs without throwing any errors and the data is not entered into the database
The file is uploaded successfully though
This is the current code I am using:
The query runs without throwing any errors and the data is not entered into the database
The file is uploaded successfully though
This is the current code I am using:
<?php
require_once('common.php');
require_once('dbconnection.php');
// IMPORTANT: Validate your SESSION variables here!!!
if(!empty($_FILES)){
// The following might need to go to a config file;
$targetDir = "uploads/";
$targetFile = $targetDir . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
// SETUP YOUR NAMED QUERY PARAMETERS.
// NAMED PARAMETERS GIVE YOU FAR MORE FLEXIBILITY IN TERMS OF REPEATED
// VARIABLES AND ORDER OF PARAMETERS
$params = [
'company' => $_SESSION['someKey'],
'fileNme' => $_FILES['file']['name'],
'it_docname' => $_SESSION['documentname'],
'date' => $date=date("Y-m-d H:i:s"), // Potentially move to DB as CURRENT_TIMESTAM
'fileSize' => $_FILES['file']['size'],
'fileType' => $_FILES['file']['type'],
'fileLink' => $_FILES['file']['link']
];
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
// ADD THIS
file_put_contents('DEBUG.LOG',print_r(['query' => $query, 'params' => $params], true) . "\n", FILE_APPEND);
//file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
//$stmt = $conn->prepare($query);
$stmt = $conn->prepare($query);
if (!$stmt->execute($params)) {
// If error logging is setup then use
// error_log(....)
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND);
}
}
}
?>
Please make sure you implement that error catching update I mentioned so that you can see any errors that might come from the prepare() code.
ASKER
gr8gonzo:
I tried your code but it did not append any data
Can you put your code in the following in case I made an error:
I tried your code but it did not append any data
Can you put your code in the following in case I made an error:
<?php
require_once('common.php');
require_once('dbconnection.php');
// IMPORTANT: Validate your SESSION variables here!!!
if(!empty($_FILES)){
// The following might need to go to a config file;
$targetDir = "uploads/";
$targetFile = $targetDir . $_FILES['file']['name'];
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
// SETUP YOUR NAMED QUERY PARAMETERS. // NAMED PARAMETERS GIVE YOU FAR MORE FLEXIBILITY IN TERMS OF REPEATED
// VARIABLES AND ORDER OF PARAMETERS
$params = [
'company' => $_SESSION['someKey'],
'fileNme' => $_FILES['file']['name'],
'it_docname' => $_SESSION['documentname'],
'date' => $date=date("Y-m-d H:i:s"), // Potentially move to DB as CURRENT_TIMESTAM
'fileSize' => $_FILES['file']['size'],
'fileType' => $_FILES['file']['type'],
'fileLink' => $_FILES['file']['link']
];
$query = <<< EOT
INSERT INTO documents (
companyName,
f_name,
f_name_itdoc,
d_date,
f_size,
f_type,
f_link)
VALUES(
:company,
:fileName,
:it_docname,
:date,
:fileSize,
:fileType,
:fileLink
)
EOT;
// ADD THIS
file_put_contents('DEBUG.LOG',print_r(['query' => $query, 'params' => $params], true) . "\n", FILE_APPEND);
//file_put_contents('DEBUG.LOG',$query . "\n", FILE_APPEND);
//$stmt = $conn->prepare($query);
$stmt = $conn->prepare($query);
if (!$stmt->execute($params)) {
// If error logging is setup then use
// error_log(....)
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $stmt->errorInfo()]) . "\n", FILE_APPEND);
}
}
}
?>
So in your code that you just pasted, line 49 is $stmt = $conn->prepare($query).
Immediately after that line, insert these lines:
Immediately after that line, insert these lines:
if($stmt === false)
{
file_put_contents('DEBUG.LOG', "Error: " . json_encode(['query' => $query, 'error' => $conn->errorInfo()]) . "\n", FILE_APPEND); }
}
ASKER
I tried that already - it does not update the debug file
So I do see one more typo, but I would have expected it to be caught as an execute() error.
'fileNme' => $_FILES['file']['name'],
That should be "fileName" to match the prepared statement variable.
Given that it's not catching that error, I'm wondering if you have PDO set up to throw exceptions and you're not displaying them.
'fileNme' => $_FILES['file']['name'],
That should be "fileName" to match the prepared statement variable.
Given that it's not catching that error, I'm wondering if you have PDO set up to throw exceptions and you're not displaying them.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Julian - I am running in php
I have Yog and MySQL Workbench installed
What is the process to run the query in the workbench
I have Yog and MySQL Workbench installed
What is the process to run the query in the workbench
ASKER
ok - I think I am there
Which query do I run as there have been several mentioned
Which query do I run as there have been several mentioned
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I get this returned:
"Error Code: 1364. Field 'sup_ticketnumber' doesn't have a default value"
The database field (sup_ticketnumber ) has a NULL setting of No
"Error Code: 1364. Field 'sup_ticketnumber' doesn't have a default value"
The database field (sup_ticketnumber ) has a NULL setting of No
ASKER
I set the fields which were not receiving data and which were set to a NULL setting of No to Yes
Now I get:
"1 row(s) affected, 1 warning(s): 1265 Data truncated for column 'd_date' at row 1"
Now I get:
"1 row(s) affected, 1 warning(s): 1265 Data truncated for column 'd_date' at row 1"
ASKER
SUCCESS!!!
ASKER
File uploaded and data entered into the database
Good job.
ASKER
Probably the best part of all this has been the troubleshooting steps - I have learnt so much
Thanks so much for the dedication and tenacity to help me get this solved
Thanks so much for the dedication and tenacity to help me get this solved
ASKER
Just noticed:
The query works in SQL Workbench but not when run through php on the web page
The query works in SQL Workbench but not when run through php on the web page
ASKER
Correction - it is now working in the php webpage
I needed to refresh the browser
I needed to refresh the browser
Thanks so much for the dedication and tenacity to help me get this solvedThat is why we are here.
ASKER
Thanks all
You are welcome.
Also, you should be using prepared statements instead of adhoc queries like this - otherwise you're vulnerable to SQL injection.