Error when inserting image in MySQL with PHP - php

I am new to PHP, I make a form to insert in a database and I can not insert an error when I want to insert the image, in the database the type of the image is "longblob", I enclose the form and the. PHPto insert in the database.
Form:
<form align="center" action="guardar.php" method="POST" enctype="multipart/form-data">
<input type="text" REQUIRED name="titulo" placeholder="Titulo.." value=""/><br><br>
<input type="text" REQUIRED name="contenido" placeholder="Contenido.." value=""/><br><br>
<input type="text" REQUIRED name="fecha" placeholder="Fecha.." value=""/><br><br>
<input type="file" REQUIRED name="imagen" /><br><br>
<input type="submit" name="Aceptar" />
</form>
PHP
<?php
include("conexion.php");
$titulo=$_POST['titulo'];
$contenido=$_POST['contenido'];
$fecha=$_POST['fecha'];
$imagen=addslashes(file_get_contents($_FILES['imagen']['tmp_name']));
$query="INSERT INTO articulos(titulo,contenido,fecha,imagen) VALUES('$titulo','$contenido','$fecha','$imagen')";
mysqli_query($conexion, $query);
$resultado=$conexion->query($query);
if($resultado){
echo "INSERT";
}else{
echo "No INSERT";
}
?>

You should not use file_get_contents(), this is the wrong function for this - it does something else entirely (you can read the manual if you are curious what this function does). Instead of using a query that injects values directly, you should also use a prepared statement, as shown below.
This will prevent SQL-injection attacks, and make sure that no data will break the query.
<?php
include "conexion.php";
$titulo = $_POST['titulo'];
$contenido = $_POST['contenido'];
$fecha = $_POST['fecha'];
$imagen = $_FILES['imagen']['tmp_name'];
$query = "INSERT INTO articulos (titulo, contenido, fecha, imagen) VALUES (?, ?, ?, ?)";
if ($stmt = $conexion->prepare($query)) {
$stmt->bind_param("ssss", $titulo, $contenido, $fecha, $imagen);
if ($stmt->execute()) {
echo "Inserted");
} else {
// Do some logging
error_log($stmt->error);
echo "Not inserted";
}
} else {
// Do some logging
error_log($conexion->error);
echo "Not inserted";
}

Related

html form radio buttons not saving string to database

I have a html form which includes a question involving three radio buttons. I want the word 'road', 'both' or gravel' to be saved to my database. This field is set up as a varchar in the database.
This is my html:
<div class="form-group">
<label>Do you prefer just road or gravel/trail cycling as well?</label>
<label for="road">Just road</label>
<input type="radio" name="bike_terrain" id="road" value="road" required/>
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="both">Both</label>
<input type="radio" name="bike_terrain" id="both" value="both" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
<label for="gravel">Just gravel/trail</label>
<input type="radio" name="bike_terrain" id="gravel" value="gravel" />
<span class="invalid-feedback"><?php echo $bike_terrain_err; ?></span>
</div>
I am then using php to validate the input is not empty:
if(empty($_POST["bike_terrain"])){
$bike_terrain_err = "Please select a bike terrain.";
} else {
$bike_terrain = isset($_POST["bike_terrain"]);
}
And php to send it to my localhost database:
if(empty($username_err) && empty($email_err) && empty($bike_terrain_err)) {
// Prepare an insert statement
$sql = "INSERT INTO users (username, email, terrain) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_username, $param_email, $param_terrain);
// Set parameters
$param_username = $username;
$param_email = $email;
$param_terrain = $bike_terrain;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location: login.php");
} else{
echo "Oops! Something went wrong. Please try again later.248";
}
}
}
(Note: I have cut out some of the other fields that I am inserting for simplicity)
$bike_terrain has previously been initialised as a string.
The problem is that nothing is being saved to the terrain field in my database and I don't know why!
Thank you very much! All suggestions, thoughts or ideas are very welcome.
Something like this (untested) should do the trick. you save the same radio with the same name so it would look like a selection somehow.
Had to quickly code from my mobile device XD
<?php
if(isset($_POST['submit'])){
$host = '127.0.0.1';
$user = 'root';
$pass = '';
$db = 'people_db'
$con = mysqli_connect($host, $user, $pass, $db) or die ('Cannot connect'.mysqli_error());
$fullname = mysqli_real_escape_string($con,$_POST['fullname']);
$gender = mysqli_real_escape_string($con,$_POST['gender']);
$q = "insert into employeedb (fullname, gender) values ('".$fullname."', '".$gender."')";
mysqli_result($con,$q);
echo 'Data Saved to Database!';
}
?>
<html>
<head>
<title>Save Radio to DB</title>
</head>
<body>
<form name="people" method="POST" action="index.php"
<input type="text" name="fullname" placeholder="Enter your name"/><br/>
<input type="radio" name="gender" value="Male"/>
<input type="radio" name="gender" value="Female"/><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

PHP mysql issue in creating an upload picture to blob undefined index _FILES

I've read about 15 threads on here, tried each and none have worked yet, the issue seems to be around uploading a picture using blob (yes I know that I shouldn't and as it scales it will cause a problem but this is only a prototype). Seem that even though I am passing in the file, $_FILES['picture'] is not set. If i remove the if and get to something like $imageName = $_FILES['picture']['name']; it says the index pictures does not exist. Any help would be appreciated greatly, thanks.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<?php include ('header.php'); ?>
<title>Add item</title>
</head>
<body>
<h1>Add item:</h1>
<form method="post" action="additem.php">
Item Name:
<input type="varchar" name="name" maxlength=64>
<br><br>
Description:<br>
<textarea name="description">
</textarea>
<br><br>
Date added:
<input type="date" name="date">
<br><br>
Picture:
<input type="file" name="picture" value="picture">
<br><br>
Shop:
<input type="varchar" name="shop" maxlength=64>
<br><br>
Type:
<input type="varchar" name="type" maxlength=15>
<br><br>
subtype:
<input type="varchar" name="subtype" maxlength=32>
<br><br>
<input type="submit" enctype="multipart/form-data" method="post" name="submit" value="Add event">
</form>
<br><br>
and my php code:
<?php
if (empty($_SESSION['username'])) {
echo "Not logged in";
exit;
} else {
if ($_SESSION['privilege'] == "student") {
echo $_SESSION['username'];
echo " does not have permission to create events ";
exit;
} else {
echo $_SESSION['username'];
echo " creating new item";
}
}
if(!empty($_POST)) {
require_once('connectdb.php');
$name = $_POST['name'];
if(empty($name)) {
echo(" You must enter an item name.");
exit;
}
$date = $_POST['date'];
if(empty($date)) {
echo(" You must enter an item add date.");
exit;
}
$shop= $_POST['shop'];
if(empty($venue)) {
echo(" You must enter an shop.");
exit;
}
if (isset($_FILES['picture'])){
$imageName = $_FILES['picture']['name'];
$imageData = $_FILES['picture']['tmp_name'];
$imageType = $_FILES['picture']['type'];
if(substr($imageType,0,5) == "image")
{
echo "this is an image";
} else {
echo "Incorrect file type";
exit;
}
$description = $_POST['description'];
$type = $_POST['type'];
$subtype = $_POST['subtype'];
$organiser = $_SESSION['username'];
try {
$stmt = $db->prepare("INSERT INTO `items` (`name`, `description`, `date`, `picturename`, `picture`, `organiser`, `shop`, `type`, `subtype`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute(array($name, $description, $date, $imageName, $imageData, $_SESSION['username'], $shop, $type, $subtype));
echo("Successful.");
} catch(PDOException $ex) {
echo("Failed to save data to database.<br>");
echo($ex->getMessage());
exit;
}
}else{
echo "file not set";
}
}
?>
</body>
</html>
You should specify a non-default encoding for your form - otherwise the browser will not upload your file at all:
<form method="post" action="additem.php" enctype="multipart/form-data">

POST method not inserting data into database table

I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.
Code is attached below, would appreciate if someone could point me into the right direction.
index.php:
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="breed">Breed</label>
<input type="text" name="breed">
<label for="age">Age</label>
<input type="text" name="age">
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connect.php";
if('submit') {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
connect.php:
<?php
$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');
?>
<?php
require "connect.php";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
Change if('submit') {
TO
if(isset($_POST['submit'])){//check if it is set
}
Also change this line:
$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');
TO
$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable
Your code is very well vulnerable to SQL injection
Using prepared statements,
$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
echo 'Saved';
} else {
echo 'Error '. $stmt->error;
}
Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests

I have an input form with a prepaired statement that should input into sql and print the input but all I get is NULL printed on the page

I have an input form with a prepaired statement that should input into sql and print the input but all I get is a blank page with the input php address. Have i missed something? I have changed the code to below but all that appears is NULL. The date field is sql type date and the string i entered into it to test is "2008-11-11", without the quotes of course.
<?php
function shutdown(){
var_dump(error_get_last());
}
register_shutdown_function('shutdown');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
header("location:index.php");
echo $conn->error;
}
$stmt->close();
$conn->close();
header("location:index.php");
}
}
?>
The html form is below
<fieldset style="width:45%"><legend>Blog data entry</legend>
<form name="Blogentry" action="Inputform.php" method="POST">
<label for="Title">Title: </label>
<input type="text" name="Title" value="" size="40"/><br>
<label for="Date">Date: </label>
<input type="text" name="Date" value="" size="40"/><br>
<label for="Country">Country: </label>
<input type="text" name="Country" value="" size="40"/><br>
<label for="bloguser">User: </label>
<input type="text" name="bloguser" value="" size="40"/><br>
<label for="Blogentry">Blog: </label>
<textarea name="Blogentry" rows="4" cols="20">
</textarea><br>
<input id="button" type="submit" name="submitblog" value="submit-blog">
</form>
</fieldset>
</body>
</html>
enable error reporting :
add on top of your script
error_reporting(E_ALL);
ini_set('display_errors', 1);
and then use prepared statements proper. As far as your script there no parameters that you are binding,
<?php
session_start();
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $conn->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
echo $conn->error;
}
$stmt->close();
$conn->close();
}
}
?>
you don't need to escape anything since you are using bind
so drop the mysqli_real_escape
you have errors in your query as I point out in the code below
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
// question marks will be replaced with data - use question marks!
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
// number of bound parameters should match number and order of question marks
$stmt->execute();

I'm throwing and error using mysqli prepared statements on an insert into my DB

Based on an earlier post I'm trying to learn prepared statements to sanitize everything properly.
Here's my form:
<form name="login" action="regi.php" method="post" accept-charset="utf-8">
<label for="username">Username: </label><br />
<input type="username" name="username" placeholder="Handle" required><br />
<input type="hidden" name="sign_up_date" value="<?php echo $_POST['sign_up_date'] ?>">
<label for="usermail">Email: </label><br />
<input type="email" name="usermail" placeholder="yourname#email.com" required><br />
<label for="password">Password: </label><br />
<input type="password" name="password" placeholder="password" required><br />
<input type="submit" value="Login">
</form>
Here's the regi.php page:
include("mysql_connect.php");
include("classes/insert.php");
if (!mysqli_query($mysqli,$stmt))
{
die('Error: ' . mysqli_error($mysqli));
}
echo "1 record added";
mysqli_close($mysqli);
Here is my insert.php page:
$user = $_POST['username'];
$email = $_POST['usermail'];
$stmt = $mysqli->stmt_init();
if (!$stmt) {
echo "Init failed";
} else {
$cmd = "INSERT INTO people (username, email, sign_up_date) VALUES (?, ?, NOW() )";
if ($stmt->prepare($cmd)) {
$stmt->bind_param('ssd', $user, $email );
$stmt->execute();
echo $stmt->affected_rows . "row(s) inserted";
$stmt->close();
} else {
echo "Prepare failed";
}
}
Here is my error message:
Localhost via UNIX socket 0row(s) insertedError:
I assume i'm doing something wrong on my insert.php page?
Any help would be greatly appreciated. Thank you.
you could write your query as a stored procedure ... this way the actual query is stored in the db and not in your php file.
also, based on what you have right now it does not look like you are inserting the correct values into the right columns in your table
here is the stored procedure approach
// update your php files so that the following variables read
$cmd = call `people`.`procedurename` (?,?)";
$stmt->bind_param($user, $email );
log into mysql and create a stored procedure with this code
DELIMITER $$
CREATE PROCEDURE `people`.`procedurename` (
IN username VARCHAR(50),
IN email VARCHAR(50)
)
BEGIN
INSERT INTO people (username, email, sign_up_date) VALUES (username, email, NOW());
END
$$
good luck :)

Categories