Issue in uploading images to MySQL database using PHP - php

I have this php code to upload image to the database, I have issue
with it and I don't know what is it, the database table name is
images and the fields are id, name VARCHAR(), photo LONGBLOB.
<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
</br>
</br>
</br>
<input type="submit" name="go" value="Upload"/>
</form>
<?php
if(isset($_POST['go'])){
if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
echo "Select a photo please";
}else {
$image = addslashes($_FILES['image']['tmp_name']);
$name = addslashes($_FILES['image']['name']);
$image = file_get_contents($image);
$image = base64_encode($image);
save_image($image , $name);
}
}
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$conn = new mysqli($servername, $username, $password);
$qry = "insert into images (photo , name) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
?>
</body>
</html>
The result is as shown in the attached screenshot:
Result

Your function neglects to mention the database - you need to supply that as one of the parameters, like:
function save_image($image , $name){
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database='xxxxxxxx';/* enter correct db name */
$conn = new mysqli( $servername, $username, $password, $database );
$qry = "insert into images (`photo`, `name`) VALUES ('$image','$name')";
$result = mysqli_query($conn,$qry);
if($result){
echo "Successfull upload";
}else{
echo "try Again";
print_r($result);
}
}
FYI that said your code is vulnerable to sql injection - better to use prepared statements!

You're not using database name in the mysqli constructor. It should be like the following:
$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);
Hope it should work now.

Related

Why I am not getting data in my database?

I am trying to POST my data in my database but unable to do... Which mistake I did here? I have simply try to print Query but it prints without any value....
If I did any mistake then let me know..
And suggest me what can I do now...
<?php
if(isset($_POST['firstname'])){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sms";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("Could not connect to the database due to the following error --> ".mysqli_connect_error());
}
//echo "success";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$mobno = $_POST['mobno'];
$dob = $_POST['dob'];
$sql1="INSERT INTO `register`(`firstname`, `lastname`, `email`, `mobno`, `dob`) VALUES ('$firstname','$lastname','$email','$mobno','$dob')";
echo $sql1;
if($conn->query($sql1) == true){
// echo "Successfully inserted";
// Flag for successful insertion
$insert = true;
}
else{
echo "ERROR: $sql1 <br> $conn->error";
}
// Close the database connection
$conn->close();
}
?>

No database selected - php and phpmyadmin

I am trying to connect my php code to my database and once I input and submit things like username, email address, and password in my html form. They will be sent to my database and shown in specific columns and there will be text like "New record has been created successfully" on my page. But for now, an error occurs instead.
The following is my php code
<?php
$visitorname = $emailaddress = $visitorpassword = $confirmpassword = "";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$visitorname = input($_POST["visitorname"]);
$emailaddress = input($_POST["emailaddress"]);
$visitorpassword = input($_POST["visitorpassword"]);
$confirmpassword = input($_POST["confirmpassword"]);
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
}
function input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if($visitorpassword == $confirmpassword){
// Create connection
$conn = new mysqli($servername, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$id = mysqli_insert_id($conn);
$sql = "INSERT INTO registereduser (id, username, emailaddress,
hashedpassword) VALUES ($id, $visitorname, $emailaddress,
$hashed_password)";
if ($conn->query($sql) === TRUE){
echo "New record created successfully";
}else{
echo "Errors " . $sql . "<br>" . $conn->error;
}
$conn->close();
}else{
echo "Passwords do not match";
}
?>
The following is the error output shown on my web page:
Connected successfullyErrors INSERT INTO registereduser (id, username, emailaddress, hashedpassword) VALUES (0, Josh5577, josh1998#hotmail.com, $2y$10$RMasEdVOskmcXbmfchLeBeUzLa5l38jXFaCQN7vMEhR8A0mU/iiC6)
No database selected
Please use below code for connection
$conn = new mysqli($servername, $username, $password, $dbname);
You can try to change
// Create connection
$conn = new mysqli($servername, $dbname);
to
// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn, $dbname);

upload file to sql sever with php

I try to upload file to a database by using php.
Here is my code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/$UploadName");
$url = "http://localhost/uploadandview/uploaded/$UploadName";
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}}?>
But i have a proplem, I can't upload any file mp3/mp4, just only upload file text, such as .doc,pdf, css, etc...
Please help me!
Try this code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db ='testdb';
// Create connection
mysql_connect($servername, $username, $password);
mysql_select_db("testdb");
if(isset($_POST['submit']))
{
$UploadName = $_FILES['UploadFileField']['name'];
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadName = preg_replace("#[^a-z0-9.]#i","",$UploadName);
if (!$UploadTmp)
{
die ("No File Selected, Please Upload Again");
} else
{
move_uploaded_file($UploadTmp,"uploaded/".$UploadName);
$url = "http://localhost/uploadandview/uploaded/".$UploadName;
mysql_query("INSERT INTO `videos` VALUE('1','$UploadName','$url')");
}} ?>

Store and Retrieve JPG in Mysql using PHP

I am trying to store jpg images into MySQL database , The insertion works but I am unable to display the results.
here is MySQL table definition:
drop table if exists product_image;
create table product_image(
id_img int not null primary key auto_increment,
name varchar(512),
img LONGBLOB NOT NULL,
id_product int not null
);
PHP script to store User input file:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" >
<input type="submit" value="Upload" name="submit">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "store";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['submit'])) {
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if (substr($imageType, 0, 5) == "image") {
$sql = "insert into product_image (name,img,id_product) values ('$imageName','$imageData','65') ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo $imageName, $imageType;
}
else {
echo "select image type:";
}
}
$conn->close();
?>
</body>
</html>
PHP script to display image:
<?php
header("content-type:image/jpg");
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "store";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$q = "select * from product_image";
$result = $conn->query($q);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$img = $row["img"];
#echo "id: " . $row["img"]. "<br>";
#echo '<img src="data:image;base64, '.$row["img"].' height="200" width="200">';
}
}
else {
echo "0 results";
}
echo $img;
$conn->close();
?>
I just see small icon when I call the PHP script to view the image. Is there any thing that i am missing.
thanks.
use something like this
<img src="data:image/jpeg;base64,<?php echo base64_encode($row['img']); ?>" class="latest_images img-responsive img-thumbnail" alt="Cinque Terre" >

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?
HTML insert form (collecting data for 2 parameters, 'user' and 'thread')
<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>
PHP code to connect to SQL, insert inputted values
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";
//create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
try this
<?php
$user = $_POST['user'];
$thread = $_POST['thread'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
//create connection
$conn = mysql($servername, $username, $password, $dbname);
//check connection
if ($conn->connect_error) {
die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";
$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");
//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);
echo "<script>window.location='select.php'</script>"; //select.php displays the full table
//close MySQL
mysql_close($sql);
?>
It might be because the default form posting method is GET.
Either change your $_POST to $_GET or add method="POST" to your form tag.

Categories