My PHP file need to save the image in a server and store the image path in a MYSQL database.
My database imageid contains table image_table as below :
create table image_table
(
ID INT not null AUTO_INCREMENT,
path varchar(256),
primary key (ID)
)
My PHP Code is as below. Image saving in the server is working fine, but throws few errors storing the image path in DB.
Error running the below PHP code :
Parse error: syntax error, unexpected '$conn' (T_VARIABLE) in C:\xampp\htdocs\appinventor\postfile.php on line 7
The PHP Code with above error:
<?PHP
$servername = "localhost";
$username = "root";
$password = "basis123";
$database = "imageid"
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
#mysqli_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO image_table (path) VALUES('$_GET['filename']')");
//mysql_query($query);
//File Transfer Logic
$data = file_get_contents('php://input');
if (!(file_put_contents($_GET['filename'],$data) === FALSE)) echo "File xfer completed."; // file could be empty, though
else echo "File xfer failed.";
// $_GET['filename'] has the file name . and C:\xampp\htdocs\myapp is the file path
echo $_GET['filename']
//mysql_close();
?>
When i remove the database connection and SQLQuery in php code the connection is successful.
Removed lines of code for successful connection and log as "Connected successful"
#mysqli_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO image_table (path) VALUES('$_GET['filename']')");
//mysql_query($query);
Where did i go wrong ?Any suggestions ?
You forgot semicolon after $database = "imageid"
$database = "imageid";
And you have extraneous parenthesis here:
$query = "INSERT INTO image_table (path) VALUES('$_GET['filename']')");
Try this:
<?php
$servername = "localhost";
$username = "root";
$password = "basis123";
$database = "imageid";
// Create connection
$conn = new mysqli($servername, $username, $password,$database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
mysqli_select_db($conn,$database);
$query = "INSERT INTO image_table (path) VALUES('".$_GET['filename']."')";//also this is unsafe
//mysql_query($query);
//File Transfer Logic
$data = file_get_contents('php://input');
if (!(file_put_contents($_GET['filename'],$data) === FALSE)) echo "File xfer completed."; // file could be empty, though
else echo "File xfer failed.";
// $_GET['filename'] has the file name . and C:\xampp\htdocs\myapp is the file path
echo $_GET['filename']
//mysql_close();
?>
Main problem:
$database = "imageid"
^----missing ;
$conn = new m
PHP strings+arrays 101: You cannot use quoted array keys within a double-quoted string, unless you use the {}-extended syntax:
$foo = "$arr['key']"; // bad
$foo = "$arr[key]"; // ok
$foo = "{$arr['key']}"; // ok
So:
$query = "INSERT INTO image_table (path) VALUES('$_GET['filename']')");
^--------^
is wrong, as well as being vulnerable to SQL injection attacks.
You need a semi colon after
$database = "imageid"
so it should be
$database = "imageid";
You also don't want to be putting user input directly into your SQL. http://en.wikipedia.org/wiki/SQL_injection
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.
I am adding data from a file to my database. Currently the location of the files are limited to only those inside directory D:/. I want to be able to support adding files from multiple directories.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "stdprt";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$filename = "d:/" . $_POST['fname'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
$sql = "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
//echo "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo "<br>";
}
?>
<h2>Uploaded Successfully....</h2>
back
If you are wanting to choose a file in another drive you can modify this line in your code and change the directory at the start.
$filename="d:/".$_POST['fname'];
So for example if you wanted to change the directory to drive F it would be like so:
$filename="f:/".$_POST['fname'];
If you wanted to enable the ability to specify a custom directory in your request then you could pass it through the same way you are passing fname. Say for example you passed your custom directory along in a key named cust_dir you could add it as the directory like so.
if($_POST['cust_dir']{
$filename=$_POST['cust_dir'].$_POST['fname'];
} else {
$filename="d:/".$_POST['fname'];
}
The code above would use a custom directory path that you passed in the $_POST variable if you passed one. If you do not pass cust_dir then it will default to directory d:/.
Here's the code:
$coinno = $_POST["CoinNo"];
$week = $_POST["week"];
$payer = $_POST["payer"];
$payee = $_POST["payee"];
$servername = "localhost";
$username = "username"; // Edited from original
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `Transactions`(`Week`,`Coin`,`Payer`,`Payee`)
VALUES ($week,$coinno,'$payer','$payee')";
if($conn->query(sql)===TRUE)
{
echo "Success";
}
else
{
echo "Error ".$sql."<br>".$conn->error;
}
$conn->close;
?>
And my error message:
Error INSERT INTO Transactions(Week,Coin,Payer,Payee) VALUE (1,2,'Bob','Carol')
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'sql' at line 1
I've tried using backticks, single quotes, etc. Even copying the generated query from phpMyAdmin did not help.
Another notable issue is that my Transactions table has a single row but when I try to select it I get 0 results. Could there possibly be a connection?
if($conn->query(sql)===TRUE)
-->
if($conn->query($sql)===TRUE)
Also, get into the habit of flipping the if around -- some functions return either FALSE or something useful. That is, they may never return TRUE. That is:
if($conn->query($sql) !== FALSE)
I have been developing a CRUD application using PHP & MySQL database.
I was succeeded by creating, displaying, updation parts. But I stuck at the deletion part of a row from a database table.
I tried my best solving all the PHP shown errors but now in final it is now showing a message which I wrote to echo in case of failure.
I request someone to please help me with this problem.
Thankyou in advance.
Code I wrote for deletion:
//include database connection
include 'db_connect.php';
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "DELETE
FROM `grocery`
WHERE `GrocerID` ='".$mysqli->real_escape_string($_GET['id'])."'
limit 0,1";
//execute query
if( $mysqli->query($query) ){
//if successful deletion
echo "User was deleted.";
}else{
//if there's a database problem
echo "Database Error: Unable to delete record.";
}
$mysqli->close();
?>
Code I wrote for delete link in display table:
//just preparing the delete link to delete the record
echo "<a href='delete.php?id={$GrocerID}'>Delete</a>";
Code I wrote for db config:
<?php
//set connection variables
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
?>
I tried this and got working, can you update the code and see if this works?
$host = "localhost";
$username = "root";
$password = "secret";
$db_name = "crud"; //database name
//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);
//check if any connection error was encountered
if(mysqli_connect_errno()) {
die("Connection failed: " . $conn->connect_error);
exit;
}
// Delete row
if ($mysqli->query (sprintf( "DELETE FROM grocery WHERE email = '".$mysqli->real_escape_string($_GET['id'])."' LIMIT 1") )) {
printf ( "Affected Rows %d rows.\n", $mysqli->affected_rows );
}
I hope this helps.
Provide a connection :
if( $mysqli->query($con, $query) ){
I have a website in PHP. I try to store the session variable $_SESSION['user_name'] to a mysql database when a logged in user visits a specific webpage on my site.
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES ('.$_SESSION['user_name'].')';
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Error message:
Notice: Undefined variable: _SESSION in /opt/lampp/htdocs/succes.php on line 16
Tried a bunch of things but can't figure it out. What is wrong here?
You need to call session_start() at the beginning of your script (before using any $_SESSION variables). Also, you need quotes around the variable in you query:
$sql = 'INSERT INTO users
VALUES ("'.$_SESSION['user_name'].'")';
Please note that this is not safe; you are wide open to SQL injection. Instead, you should use prepared statements:
<?php
$servername = "localhost";
$username = "user1";
$password = "user1";
$dbname = "payment";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = 'INSERT INTO users
VALUES (?)';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $_SESSION['user_name']);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Before you use any $_SESSION variables you need to call session_start().
Of topic a bit though, something to look into PDO. It can be a bit a tad slower than mysqli() however supports many more Database types. Here is a good article on Tuts+ explaining some of the differences as well as explaining essential security steps.
If I could be a bit biased I have created a PHP Class for PDO Connections which can be found on GitHub