Insert images into a database - php

Im trying to upload an image to a mysql database, but when I upload the image I receive the message of confirmation, but when i check my database the image row is empty, what am I doing wrong?
<?php include "connection.php"; ?>
<?php
$n=$_POST["num"];
$t=$_POST["texto"];
$i=$_POST["imagem"];
$image = addslashes(file_get_contents($_FILE['$i']['tmp_name']));
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
}
$sql = "UPDATE servicos SET texto='$t', imagem='{$image}' where nmr=$n" ;
if ($connect->query($sql) === TRUE) {
echo "informação atualizada";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
?>
<html>
<body>
<div class="formulario" style="width: 100%; height: 100%;">
<form enctype="multipart/form-data" name="form1" target="apresenta" method="post" action="menu2.php" style="position:absolute; top:70;left:10
border:thin; border-style:none;">
<label> Atualizar dados </label><br>
Numero: <input type="text" name="num" value=""><br>
Texto: <input type="text" name="texto" value=""><br>
Imagem: <input type="file" name="imagem" value=""><br>
<input type="submit" name="submit" value="enviar">
<input type="reset" value="limpar">
</form>
</div>
</body>
</html>

Besides all the comments stating "You shouldn't store files in tables because...", this is what works (with PHP 7):
<?php
if(isset($_POST['submit'])) {
var_dump($_FILES);
$dbh = new PDO("mysql:host=127.0.0.1;dbname=test", "root", "");
$stm = $dbh->prepare("INSERT INTO test_img (cont) VALUES (?)");
$stm->execute(array(file_get_contents($_FILES['fileinput']['tmp_name'])));
}
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="fileinput"><br>
<button name="submit">Upload</button>
</form>
Possible error sources:
$connect->query($sql) === TRUE should be $connect->query($sql) !== false
The entry you want to UPDATE does not exist
imagem='{$image}' is a rather "hacky" way do insert variables, use concatenation: $sql = "UPDATE servicos SET texto='".$t."', imagem='".$image."' where nmr=".$n;
Hope this helps.

Related

Update SQL Statement with id=%d not working

Hi for some reason my update statement is not working, most probably because of the id=%d, its not getting the id for the statement i think but its finding the id because it is listed in the url (shown Below). What is the problem please ?
This works when i Insert a number for the id, example : id=77, so most probably the problem is the %d how can i get it to find the id with the %d ?
http://localhost/test/edit.php?id=77
<?php
ob_start();
session_start();
include_once 'logindb.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
if((isset($_POST['submit']))){
if((!isset($_POST['title'])) || (!isset($_POST['times'])) ){
echo "All values must be set";
}
else{
$title = $_POST['title'];
$times = $_POST['times'];
$film_id = $_GET['id'];
$upfile = 'Uploads/posters/'.$_FILES['userfile']['name'];
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upfile)){
echo "File moved into folder";
header( "Location: index.php" ) ;
}
else{
echo "Problem: could not move image file to destination directory";
}
$upfile2 = 'Uploads/trailers/'.$_FILES['userfile2']['name'];
$format1 = "UPDATE films SET titles = '$title', ftimes = '$times', poster = '$upfile', trailer = '$upfile2' WHERE id = %d";
$query = sprintf($format1, $film_id );
$result = mysqli_query($conn, $query)
or die("Error in query: ". mysqli_error($conn));
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Empire.css"/>
<script type="text/javascript" src="script.js"> </script>
<title>Movie Form</title>
</head>
<body class="formola">
<div class="form-style-5">
<p class="top"> List Movies </p>
<form method = "post" action="edit.php" enctype="multipart/form-data">
<fieldset>
<legend><span class="number">1</span> Details </legend>
<input type="text" name="title" placeholder="Movie Title">
<input type="text" name="times" placeholder="Times">
</fieldset>
<fieldset>
<legend><span class="number">2</span> Attachments </legend>
<div class="form-group ">
<label> Film Poster <br> </label>
<input type="hidden" class="form-control" name="MAX_FILE_SIZE" value="100000000">
Upload this Film Poster: <br> <input name="userfile" id="userfile" type="file"> <br>
<input type="hidden" class="form-control" name="MAX_FILE_SIZE" value="10000000">
Upload this Trailer: <br> <input name="userfile2" id="userfile2" value="10000000" type="file"> <br>
</div>
</fieldset>
<input type="submit" name = "submit" value="Upload" />
</form>
</div>
</body>
</html>

Data not inserting in database when submitted

I've set up a form to insert data into a database. It's connected to it fine and can display records with no issues. However, when I want to insert data I click the submit button it removes it from the form but doesn't insert it into the db. I've tried rewriting it about 3 times now using 2 different databases but just can't figure out where I'm going on.
<html>
<head>
</head>
<body>
<form action="input.php" meathod="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
You have few typos "meathod=post" should be method="post",mysql_query($sql,$conn) should be mysqli_query($conn,$sql) and mysqli_select_db("test",$conn) should be mysqli_select_db($conn,"test")
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db($conn,"test");
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysqli_query($conn,$sql);
mysqli_close($conn);
};
?>
</body>
</html>
you have written "meathod=post" instead of "method=post"
also I have changed
$sql="INSERT INTO users(username,password) VALUES ('$_POST[username]','$_POST[password]')";
to
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
this style much more better
<html>
<head>
</head>
<body>
<form action="lol.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES ('" . $_POST['username'] . "','" . $_POST['password'] . "')";
mysql_query($sql,$conn);
mysqli_close($conn);
};
?>
</body>
</html>
I think problem is here
mysql_query($sql,$conn);
Replace with
mysqli_query($conn,$sql);
I hope this code will help you
<html>
<head>
</head>
<body>
<form action="input.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit">
</form>
<?php
if( isset($_POST['submit'])){
//connecting to a databse
$conn = mysqli_connect("localhost","root","");
mysqli_select_db("test",$conn);
if($conn){
echo 'connected';
}
else {
die('failed to connect');
}
$sql="INSERT INTO users(username,password) VALUES (".$_POST["username"].",".$_POST["password"].")";
mysqli_query($conn,$sql);
mysqli_close($conn);
?>
</body>
</html>

html form to insert in mysql with php

I want to have form which insert data into mysql db.
CODE - index.php
<form action="index3.php" method="POST"/>
Kunde: <input type="text" name"Kunde">
<br/>
Produkt: <input type="text" name"Produkt">
<br/>
Produktversion: <input type="text" name"Produktversion">
<br/>
Menge: <input type="text" name"Menge">
<br/>
<input type="submit" value"Insert">
</form>
CODE - index3.php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value1 = $_POST['Kunde'];
$value2 = $_POST['Produkt'];
$value3 = $_POST['Produktversion'];
$value4 = $_POST['Menge'];
$sql = "INSERT INTO `Aufträge` (`id`, `Datum`, `Kunde`, `Produkt`, `Produktversion`, `Menge`) VALUES (NULL, CURRENT_TIMESTAMP, '$value1', '$value2', '$value3', '$value4')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Looking in phpmyadmin; I created new entrys, but only id and Datum are filled values, the others are empty. 'id' and 'Datum' are automatically set because of identifier and currenttimestamp for those.
Whats wrong with $value1 - $value4?
Change your index.php as below:
<form action="index3.php" method="POST">
Kunde: <input type="text" name="Kunde">
<br/>
Produkt: <input type="text" name="Produkt">
<br/>
Produktversion: <input type="text" name="Produktversion">
<br/>
Menge: <input type="text" name="Menge">
<br/>
<input type="submit" value="Insert">
</form>

Submitting HTML form to PHP file

I have created two files on remote server. One is html form which asks to enter some fields and another is a php file which will get all the data and insert into the database.
For this from html file on click of submit button I am calling php file, but the file is not getting execute I think because when I click on submit it again reloads the same html page.
html :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form method="post" >
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br>
Enter option 2 : <input name="opt2" type="input"> <br><br>
Enter option 3 : <input name="opt3" type="input"> <br><br>
Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value = "Submit" onClick = "uploadQuestion.php">
</form>
</body>
</html>
php file:
<?php
$question=$_POST['question'];
$option1=$_POST['opt1'];
$option2=$_POST['opt2'];
$option3=$_POST['opt3'];
$option4=$_POST['opt4'];
$ans=$_POST['ans'];
$db_server = mysql_connect("address","username","pass");
if(!$db_server) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question','$option1',$option2,$option3,$option4,$ans)";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
I also tried this way :
<input type="submit" value = "Submit" onClick = "http://address/uploadQuestion.php">
But nothing is working. Whats going wrong here? I am a beginner in web development,, can anyone help please? Thank you..
EDIT :
$database = new Database('addredd','username','pass','handbook');
$dbConnection = $database->getDB();
$stmt = $dbConnection->prepare("insert into questions(question,answer_a,answer_b,answer_c,answer_d,answer) values(?,?,?,?,?,?)");
$stmt->execute(array($question,$option1,$option2,$option3,$option4,$ans));
I tried to use pdo statement but getting this error :
Fatal error: Class 'Database' not found in /var/www/html/uploadQuestion.php on line 12
EDIT2 :
I am trying to upload one file on server and want to save it in database also, so for this I have created 2 files one is index.php and another is uploadFile.php.
As you shown now I used pdo for this but when I click on upload image again same page is getting load.
index.php
<form action="index.php" method="post" enctype="multipart/form-data">
<p> Select image to upload:</p>
<input name = "file" type="file" id="fileToUpload"><br><br>
Enter chapter name :
<input name = "chapterName" type = "text"><br><br>
<input type="submit" value = "Upload Image">
</form>
<?php
if (isset($_FILES['file']['tmp_name']))
{
$ch = curl_init();
$cfile = new CURLFile($_FILES['file']['tmp_name'],$_FILES['file']['type'],$_FILES['file']['name']);
$data = array("myfile" => $cfile);
curl_setopt($ch, CURLOPT_URL, "http://host/NewProject/uploadFile.php");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOTP_POSTFIELDS, $data);
$response = curl_exec($ch);
if($response == true)
{
echo "File posted";
}
else{
echo "Error: " . curl_error($ch);
}
}
?>
uploadFile.php
<?php
ini_set('display_errors', 1);
if(isset($_FILES['myfile']['tmp_name']))
{
$path = "files/" . $_FILES['myfile']['name'];
move_uploaded_file($_FILES['myfile']['tmp_name'], $path);
$chapterName=$_POST['chapterName'];
$dbh = new PDO('mysql:host=host;dbname=database_name','username', 'password');
$stmt = $dbh->prepare("INSERT INTO chapters (title,file) VALUES (?, ?)");
$stmt->execute(array($chapterName,$path));
if ($dbh->lastInsertId())
{
echo 'File upploaded.';
}
else
{
echo 'File could not upload.';
}
}
?>
Please help.. Thank you..
First repair your form, type="" can't be named input u can check here https://www.w3schools.com/tags/att_input_type.asp
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="text"> <br><br>
Enter option 2 : <input name="opt2" type="text"> <br><br>
Enter option 3 : <input name="opt3" type="text"> <br><br>
Enter option 4 : <input name="opt4" type="text"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="text"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then yours php code
<?php
// mysql connection
$db_server = mysql_connect("address","username","pass");
// check for mysql connection
if(!$db_server)
{
die("Database connection failed: " . mysql_error());
}
else
{
// check if database exists
$db_select = mysql_select_db("mlm",$db_server);
if (!$db_select)
{
die("Database selection failed:: " . mysql_error());
}
}
// escape post variables
$question = mysql_real_escape_string($_POST['question']);
$option1 = mysql_real_escape_string($_POST['opt1']);
$option2 = mysql_real_escape_string($_POST['opt2']);
$option3 = mysql_real_escape_string($_POST['opt3']);
$option4 = mysql_real_escape_string($_POST['opt4']);
$ans = mysql_real_escape_string($_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
?>
Or php with mysqli
<?php
// host, username, password, database name
$db_server = mysqli_connect("address", "username", "pass", "mlm");
// check for connection
if(!$db_server)
{
die("Database connection failed: " . mysqli_error($db_server));
}
// escape post variables
$question = mysqli_real_escape_string($db_server, $_POST['question']);
$option1 = mysqli_real_escape_string($db_server, $_POST['opt1']);
$option2 = mysqli_real_escape_string($db_server, $_POST['opt2']);
$option3 = mysqli_real_escape_string($db_server, $_POST['opt3']);
$option4 = mysqli_real_escape_string($db_server, $_POST['opt4']);
$ans = mysqli_real_escape_string($db_server, $_POST['ans']);
// make query
$sql = "INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ('$question', '$option1', '$option2', '$option3', '$option4', '$ans')";
// check if query runs
if (!mysqli_query($db_server, $sql))
{
die('Error: ' . mysqli_error($db_server));
}
?>
Or php with prepared statements
<?php
// mysql connection
$dbh = new PDO('mysql:host=adress;dbname=database_name', 'username', 'password');
// escape post variables
$question = $_POST['question'];
$option1 = $_POST['opt1'];
$option2 = $_POST['opt2'];
$option3 = $_POST['opt3'];
$option4 = $_POST['opt4'];
$ans = $_POST['ans'];
$stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer) VALUES ( ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($question, $option1, $option2, $option3, $option4, $ans));
if ($dbh->lastInsertId())
{
echo 'Sucess.';
}
else
{
echo 'Fail.';
}
?>
Change your from code to this
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<form action="uploadQuestion.php" method="post" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="input"> <br><br>
<p> Enter options :</p>
Enter option 1 : <input name="opt1" type="input"> <br><br> Enter option 2 : <input name="opt2" type="input"> <br><br> Enter option 3 : <input name="opt3" type="input"> <br><br> Enter option 4 : <input name="opt4" type="input"> <br><br>
<p> Enter correct answer :</p>
<input name="ans" type="input"> <br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

PHP When i press the login button nothing happen

I was trying to create a login page, but it doesn't seem to work. When I enter details and click login. Nothing happens. I try to login again, still nothing happens. I want to happen is when i login a popup window will appear and i will be directed to the homepage
<?php
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class = "boxlog1"
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
}
else{
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
Add the page to the form action
For example:
<form action"login.php">
Or use
<form action"<?php echo $_SERVER['PHP_SELF']; ?>">
And close your div tag with '>', so
<div class="boxlog1">
Working example
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log'])){
$c_email = $_POST['uname'];
$c_pass = $_POST['lpass'];
$sel_c = "select * from customers where customer_pass='$c_pass' AND customer_email='$c_email'";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer == 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
And here with updated security against SQL Injection. Dont forget to encrypt your password so it cannot be stolen
<?php
if (!isset($_SESSION)) { session_start(); }
$con = mysqli_connect("localhost","root","","onlineshop");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
<div class="boxlog1">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="text" name="uname" placeholder="Username"class="username" required />
<input type="text" name="lpass" placeholder="Password" class="passwordl" required />
<input type="submit" value="Log In" class="log" name="log"/>
</form>
<p class="forget">Forget password</p>
</div>
<?php
if (isset($_POST['log']) && isset($_POST['uname']) && isset($_POST['lpass'])){
$c_email = bin2hex(htmlspecialchars($_POST['uname']));
$c_pass = bin2hex(htmlspecialchars($_POST['lpass']));
$sel_c = "SELECT * FROM customers WHERE customer_pass=UNHEX('$c_pass') AND customer_email=UNHEX('$c_email')";
$run_c = mysqli_query($con, $sel_c);
$check_customer = mysqli_num_rows($run_c);
if($check_customer === 0){
echo "<script>alert('Password or Email is incorrect!')</script>";
exit();
} else {
$_SESSION['customer_email']=$c_email;
echo "<script>alert('login!')</script>";
echo "<script>window.open('paymnet.php','_self')</script>";
}
}
?>
I did'nt changed really much. Just closed your div tag correctly and added an action. However, it does work without the action filled in.

Categories