Storing multiple images in MySQL database with PHP - php

I am new to PHP.
I am trying to add multiple images with text to a database and I'm stuck. If I select one, it gets stored. If I select multiple, it's left as blank in the database.
I need help to resolve this. Plus, I am confused: is one table for images in db ok? I mean, is there a special datatype or way to have multiple images on the same entry in a database?
Here's my code:
<html>
<body>
<form class="container" enctype ='multipart/form-data' action="add.php" method="post">
<label><b> Name: </b></label><br><br>
<input type="text" name="name"><br><br>
<label><b> Type: </b></label><br><br>
<input type="text" name="type"><br><br>
<label><b> Detail: </b></label><br><br>
<input type="text" name="detail"><br><br>
<label><b> Area: </b></label><br><br>
<input type="text" name="area"><br><br>
Select image to upload:
<input type="file" name="filename" size='10000' multiple>
<input type="submit" value="Upload Image">
</form>
<?php
// error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'login.php';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password, $db_database);
if (!$db_server) die("unable to connect to mysqli:" . mysqli_error());
mysqli_select_db($db_server, "dbase1") or die("db not selected" . mysqli_error());
$name = $_POST["name"];
$type = $_POST["type"];
$detail = $_POST["detail"];
$area = $_POST["area"];
if($_FILES)
{
$namee = $_FILES['filename']['name'];
move_uploaded_file($_FILES['filename']['tmp_name'], $namee);
echo "uploaded image'$namee'<br><img src ='$namee'>";
}
$source= "pictures/".$namee;
$sql = "INSERT INTO adprop (name, type, text,area,filename) VALUES ('$name','$type','$detail','$area','$source')";
$db = $db_server->query($sql);
?>
</body>
<html>
Thanks in advance for your help!

For example if you want save multiple image paths in a field, you can add them to db as below:
/image_folder/image_name1.jpg,/image_folder/image_name2.jpg
And use split and for loop to print them dynamically in user interface.

Related

PHP does not upload file on localhost

I am reading "Head first PHP book" and stumbled at chapter 5 where file upload is implmented. I did it on XAMPP on windows 7. The path to the file is the following:
htdocs-->chapter5-->form.php
Here is my simplified version of the original code.
<html>
<head>
<title>Guitar Wars - Add Your High Score</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<head>
<body>
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
<hr />
<h2>Guitar Wars - Add Your High Score</h2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
</body>
The whole idea is the following. User enters his name and score and selects file for upload via self-submitting html form:
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="32768">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<?php if (!empty($name)) echo $name; ?>" /><br />
<label for="score">Score:</label>
<input type="text" id="score" name="score" value="<?php if (!empty($score)) echo $score; ?>" />
<br />
<label for="screenshot">Screenshot:</label> <input type="file" id="screenshot" name="screenshot"> <hr/>
<input type="submit" value="Add" name="submit" />
</form>
then the data is processed by php script in the same file:
<?php
if (isset($_POST['submit']))
{
// Grab the score data from the POST
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot=$_FILES['screenshot']['name'];
if (!empty($name) && !empty($score) && !empty($screenshot))
{
// Connect to the database
$dbc = mysqli_connect('localhost', 'root', '') or die("could not connect to the database");
mysqli_select_db($dbc, "store") or die("could not choose the database");
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
// Write the data to the database
$query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query) or mysqli_errno();//die ("could not create record");
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
mysqli_close($dbc);
}
else
{
echo '<p class="error">Please enter all of the information to add your high score.</p>';
}
}
?>
When i try to submit the form for processig the message is
problem uploading
which suggests that move_uploaded file failed. What i did are the following:
Chagged permission of the entire htdocs folder - did not work.
Created image folder within the chapter5 directory and changed its permission it did not work. I.e. created directory image as
htdocs-->chapter5-->image
and changed permissions of the directory. then I called move_uploaded_file as
move_uploaded_file($_FILES['screenshot']['tmp_name'],
'/image/.$screenshot') or die("problem uploading");
this approach did not work
Created image directory in the htdocs directory and tried the following call
move_uploaded_file($_FILES['screenshot']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/image/.$screenshot') or die("problem uploading");
every time i have
probem uploading
text written on the page after form submission. I looked at file_upload record in the php.ini file everyhting seem fine:
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir="C:\xampp1\tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize=40M
; Maximum number of files that can be uploaded via a single request
max_file_uploads=2
I also changed the permmision of 'C:\xampp1\tmp'
Nothing worked. Can anybody suggest what am i doing wrong?
First things first, turn on error reporting so you can see the actual error/warning that is happening - How do I get PHP errors to display?
I ran your code and it works if the destination directory actually exists. One approach to ensuring that it exists is to create the directory on the fly.
Not sure if this is the right location for you, but using ./image/ will create the image in the directory where your script is executing. You can play around with $destinationDirectory until you get your desired location and it should continue to work.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
...
if (!empty($name) && !empty($score) && !empty($screenshot)) {
$destinationDirectory = './image/';
// Check if the destination is a directory. If not, create it.
if (!is_dir($destinationDirectory) && !mkdir($destinationDirectory)) {
die("Error creating folder $destinationDirectory");
}
$finalPath = $destinationDirectory . $screenshot;
if (!move_uploaded_file($_FILES['screenshot']['tmp_name'], $finalPath)) {
die("problem uploading");
}
...
'/image/.$screenshot' likely should be '/image/'.$screenshot
#waterloomatt, yes, this is just typo
You should edit your question with the real code then otherwise, it will throw people off.
And final note - $query = "INSERT INTO scores VALUES (0, NOW(), '$name', '$score', '$screenshot')";
This code is fully susceptiable to SQL injection because you're passing user supplied data directly to your database. Look into prepared statements - https://phpdelusions.net/pdo#prepared
The solution was pretty obvious. I created simple form.html file and separate form.php form handler. When 2 are separate then everything works fine. When the form is self-submitting it gave me error messages. Looks like this is related to form submission.

Adding a string to a database

I'm trying to add a string to my database, where I have two columns: "id" and "image". The "id" column is supposed to increment and the "image" column should get a string. This is my phpcode:
<?php
$servername = "somename";
$username = "someusername";
$password = "somepssword";
$dbname = "somedatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$image = $_POST["image"];
$sql = "INSERT INTO photos (image) VALUES ('$image')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
the html form:
the html form:
<body>
<form method="post" action="phpcode.php">
<input type="text" name="message" size="55">
<input type="submit"name="submit" value="Send">
</form>
</body>
</html>
I use this app to send a post to the server: https://www.getpostman.com/ yet for some reason it only increments a value id and doesn't receive anything for image like here:
enter image description here
<form method="post" action="phpcode.php">
<input type="text" name="message" size="55">
<input type="submit"name="submit" value="Send">
</form>
As suspected, your name attribute field is wrong as it does not correspond to what you are trying to post .
Change to
<form method="post" action="phpcode.php">
<input type="text" name="image" size="55">
<input type="submit"name="submit" value="Send">
</form>
When submitting forms, PHP reads from your "name" attribute on your form. That is what you are posting to your controller file.

Inserting HTML Form data into MySQL with PHP

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Connecting form to SQL Database

I am able to connect to mysql database however I can not display data from my form to my database. I am not sure why this is happening but I have been able to retrieve data from my database I just can not enter information into it. For now I am just trying to enter First_Name. I also get no errors when entering in data to the form. Any help would be greatly appreciated!!
<p>
<form name="input1" action="http://seanfagan.webuda.com/Final/club.php" method="post">
First_Name:<input type="text" name="First_Name"><br>
Last_Name: <input type="text" name="Last_Name"><br>
Club_Name: <input type="text" name="Club_Name"><br>
Email: <input type="text" name="Email"><br>
Club_Type: <input type="text" name="Club_Type"><br>
Members: <input type="text" name="Members"><br>
<input type="submit" value="Send"><br>
</form>
<?php
$mysql_host = "mysql14.000webhost.com";
$mysql_database = "a9576602_Final";
$mysql_user = "a9576602_Final";
$mysql_password = "*****![enter image description here][1]";
$mysql_error = "Could not connect to database!";
$conn = mysql_connect($mysql_host, $mysql_user, $mysql_password) or die ("$mysql_error");
$select_db= mysql_select_db('a9576602_Final') or die ("Couldn't select database!");
$value = $_Post['input1'];
$sql = "INSERT INTO Club (First_Name) VALUES ('First_Name')";
if (!mysql_query($sql)) {
die('Errorss: ' . mysql_error());
}
mysql_close();
?>
</p>
Assuming your connection with the database is okay. You can put a <name> attribute for your submit button to serve as a reference for sending your form via $_POST method:
<input type = "submit" name = "input1" value = "Submit">
Then using this, you can trigger your insert statement:
<?php
if(isset($_POST['input1']))
{
// make sure you also declare the variables in your form such as the first name, etc.
$firstName = $_POST['First_Name'];
mysql_query("INSERT INTO Club (First_Name) VALUES ('$firstName')");
}
?>
Hope this helps you :D

Inserting data to database via web form

I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories