Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
this mycode
I'am try to edit but no success.
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup);";
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
you dont execute your query. You have to use your object to the database for query.
try
{
$bdd = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8', 'root', 'yourpassword',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject(filename) VALUES($fileup)";
$result=$bdd->query($strSQL);
if(!$strSQL){
echo "<h1>Error Store FileName2DB<h1>";
exit;
}
echo "Upload Complete<br>";
}
You are not using mysql extension for executing your query. Other example is about to PDO.
You can also INSERT the new row by using mysqli_* extension.
MYSQL procedural structure:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(move_uploaded_file($_FILES["filUpload"]["tmp_name"],"docfile/".$_FILES["filUpload"]["name"]))
{
//*** Insert Record ***//
$file = $_FILES["filUpload"]["name"];
$fileup = mysql_real_escape_string($file);
$strSQL = "INSERT INTO fileproject (filename) VALUES ('$fileup')";
// here you need to use mysqli_* extension
if(mysqli_query($conn, $strSQL)){
echo "Upload Complete<br>";
}
else{
echo "<h1>Error Store FileName2DB<h1>";
// exit;
}
}
mysqli_close($conn); // DATABASE CONNECTION CLOSE
?>
Side note:
As I mentioned in comments $fileup value is a string value so you need to use single quotes between the variable.
Related
This question already has answers here:
PHP: How to check if image file exists?
(22 answers)
Closed 5 years ago.
Can someone please help me to make this script check if the file exists, before it truncate the table.
If filename not exists, I want to stop the import.
<?php
//set the connection variables
$hostname = "host";
$username = "username";
$password = "pass";
$database = "database";
$filename = "filename.csv";
//connect to mysql database
$connection = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($connection));
mysqli_query($connection, "TRUNCATE TABLE `my_tablename`");
// open the csv file
$fp = fopen($filename,"r");
//parse the csv file row by row
while(($row = fgetcsv($fp,"500",",")) != FALSE)
{
//insert csv data into mysql table
$sql = "INSERT INTO Pristabell (Produkt, Pris, Rabattkr, Rabattprosent, Lagerstatus, Butikk, TAGS) VALUES('" . implode("','",$row) . "')";
if(!mysqli_query($connection, $sql))
{
die('Error : ' . mysqli_error($conection));
}
}
fclose($fp);
//close the db connection
mysqli_close($connection);
?>
Thanks :-)
http://php.net/manual/en/function.file-exists.php
if(file_exists($pathtofile)){
//do import
}else{
//stop
}
One simple solution is use
file_exist;
in an if() chunk.
Before the while(), if true continue else exit or trow an exception.
This question already has answers here:
Empty values being added to all mysql rows instead of just the target row
(2 answers)
Closed 6 years ago.
I am not so sure how to process an image in PHP to put it into a blob type in MYSQLI. Here is my code so far...
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now the value of the image is not null so the image is processed. But I cant seem to get it processed. Normally I make a variable $var = $_POST['cf']; then I add that into the query. I also tried $var = $_FILES['cf']; but it wont process. Is there something else I need to do to it to make it send/process properly?
Edit based on answer
I changed my PHP to something that resembles an answer
<?php
$servername = ""; //Taken out for stack overflow question
$username = ""; //Taken out for stack overflow question
$password = ""; //Taken out for stack overflow question
$dbname = ""; //Taken out for stack overflow question
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
if (!empty($_FILES['cf'] && $_POST['category']))
{
try
{
$file = $conn->real_escape_string($_FILES['cf']['tmp_name']);
$filecontents = File_Get_Contents($file);
$filecontentssafe = $conn->real_escape_string($filecontents);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
echo 'Query successful';
}
catch(Exception $e)
{
echo 'Could not perform action' + $e;
}
}
else
{
echo 'Empty file';
}
}
mysqli_close($conn);
?>
Now I see Query successful, however.. nothing goes into the database.
Edit - added retrieve file
<?php
$servername = "";
$username = "";
$passcode = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $passcode, $dbname);
if (!$conn)
{
echo 'Could not connect';
}
else
{
try
{
$sql_query = mysqli_query($conn, "SELECT * FROM `adDatabase`");
while ($row = mysqli_fetch_array($sql_query))
{
$id = $row['ID'];
$img = $row['img'];
$image = '<img src="data:image/png;base64,'.base64_encode( $row['food'] ).'" style="height: 12em; width: 12em; margin: 1em; padding: 0.9em; " >';
echo $image;
}
}
catch(Exception $e)
{
echo $e;
}
}
?>
How I retrieve information
By the time you call mysql, $file only contains a path to the temporary uploaded file, not the data you want.
If you want MySQL to look at the file's path, and load its contents directly into your database, have a look at the MySQL function LOAD_FILE() here: http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_load-file
Otherwise, if you'd like to do this in PHP, you'd want to pull the file's contents into a variable with something like
$file_contents=File_Get_Contents($file);
... and then use
$file_contents_safe=$conn->real_escape_string($file_contents);
before sticking $file_contents_safe into the database. Some people also like to Base64 encode.
Edit: Please also keep injection vulnerabilities in mind, as others have suggested. The name of the temporary file, and anything else coming in from post/apache shouldn't be trusted on its own.
If you don't have to stick with saving the blob content in the database, you could only save the file name in the database and do a regular file upload to a selected location. For that, you will need to add this before adding the content in the database
$tmp_name = $_FILES["filename"]["tmp_name"];
$name = $_FILES["filename"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
And after uploading the file, you just need to store it's name in the database instead of storing the blob content. When displaying, you just need to access the actual file in your upload folder and show it. It's much cleaner solution, especially if you don't have to migrate files between servers.
The whole code would look something like this:
if (!empty($_FILES['cf'] && $_POST['category']))
{
$tmp_name = $_FILES["cf"]["tmp_name"];
$name = $_FILES["cf"]["name"];
move_uploaded_file($tmp_name, "YOUR_UPLOAD_DIR/{$name}");
$file = $conn->real_escape_string($name);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.") VALUES(".$file.")");
}
Then when accessing it, you will need to pull the data from the database and just display it. If it is an image, it could be
<img src="<?php YOUR_UPLOAD_DIR.'/'.$name ?>"/>
Otherwise:
To insert the image data in your database do:
$content = file_get_contents($tmpName);
$file = $conn->real_escape_string($content);
$mime_type = mime_content_type($tmpName);
mysqli_query($conn, "INSERT INTO adDatabase(".$category.", mime_type) VALUES(".$file.", ".$mime_type.")");
Note I added a mimetype to the insert, because you will need it in order to be able to display the file properly later.
Then, when you want to display it, just pull the content from the db and echo it together with the proper header.
header('Content-type:'.$mime_type);
echo $content;
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm creating a form where users can enter information and it will enter into the database on the website:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Only problem. It will work for me great because I can manually enter the feilds of my database information
($servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";)
But I am planning on releasing this form out to the public and I want them to not have to edit every single .php file (theres going to be about five php files)
How can I have it so they can "set it up" the first time they install these forms on their site.
You can solve this by having all the database settings inside a separate file, e.g. dbsettings.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
?>
In the file that you would normally do the database connection, instead of just connecting your database using:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
You would include the database settings file first.
<?php
include 'dbsettings.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This is how you do it in PHP. You will see similar setup used in Wordpress, and all other PHP frameworks like Laravel, FuelPHP, CodeIgniter etc (it might be a good idea to use these for bigger projects).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
It's possible to create a mysql connection from localhost to another server using php, if it's possible, how? Thanks!
$host_name = "www.yourdomain.com";
$database = "pdo"; // Change your database name
$username = "root"; // Your database user id
$password = "test"; // Your password
try {
$dbo = new PDO('mysql:host='.$host_name.';dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Yes it is possible.You must have the username and password of that domain in which you want to connect.
mysqli_connect("www.domain.com","username","password","database_name")or die("Error " . mysqli_error());
Yes, Simply pass following details about your server:
<?php
$servername = "your-server-name-or-ip";
$username = "your-server-username";
$password = "your-server-password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
$url = 'mysql:host=xxx.xxx.xxx.xxx;dbname=xxxxxx'
$username = xxx;
$password = xxx;
$db = new PDO($url, $username, $password);
$query = $db->query('select * from some_table');
$query->execute();
$res = $query->fetchAll(PDO::FETCH_ASSOC);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
How do i write the connection string to connect to mysql database with this info:
Using php connection string
Database Details:
phpmyadmin url: https://medicalng.com/phpmyadmin
host: localhost
database: wlfmedic_ptest1
username: wlfmedic_ptest1
password: Prog#te$t104
Use mysqli. mysqli connection is like this:
$host = "localhost";
$database = "wlfmedic_ptest1";
$username = "wlfmedic_ptest1";
$password = 'Prog#te$t104';
$connection = mysqli_connect($host, $username, $password, $database);
if(mysqli_connect_errno()){ //To show error if fails to connect
die(mysqli_connect_error());
}
Something basic, not secure tho.
<?php
mysql_connect(localhost, ##YOUR USERNAME##, ##YOUR PASSWORD##);
mysql_select_db('##YOUR DATABASE NAME##');
$result = mysql_query("SELECT * FROM emails");
?>
and updated mysqli http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
<?php
$db_hostName="localhost";
$databaseName= "wlfmedic_ptest1";
$db_userName= "wlfmedic_ptest1";
$db_password= "Prog#te$t104";
$con=mysql_connect($db_hostName,$db_userName,$db_password);
if(!$con){
die ("Could Not successfully with DataBase".mysql_error());
}else{
echo "Connect connect with succssfully .";
}
$db=mysql_select_db($db_databaseName,$con);
if(!$db)
{
echo "Can notConnect with Bd Social";
}
else
{
echo "Conncet With Bd Social";
}
?>
try this ..
<?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
print "Database Found ";
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
}
?>
also you can refer this link