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
Related
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";
}
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();
<?php
$con = mysqli_connect("localhost", "root", "" , "prosports1");
if(!isset($con)) {
die("Connection failed !!!");
}
if(isset($_POST['send'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$query = "INSERT INTO review VALUES
('','$name','$email','$contact','$subject','$message')";
$res = mysqli_query($con,$query);
if(isset($res)) {
//header("Location: homepage.php");
}
}
?>
i have used this code to insert the data to database[phpmyadmin]
but it's not working
what to do
The following is an example code for POST method. It worked for me. Follow the pattern, there isn't much of any change from your code.
<form action="new.php" method="post">
ID:<input type="text" name="id">
Name:<input type="text" name="name">
age:<input type="text" name="age">
place:<input type="text" name="city">
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit']))
{
$con = mysqli_connect("localhost", "username", "password","db_name");
$sql = "INSERT INTO employee VALUES ('$_POST[id]','$_POST[name]','$_POST[age]','$_POST[city]')";
mysqli_query($con,$sql);
echo "Data Inserted<br>";
mysqli_close($con);
}
?>
Don't forget to change the action page and essential details. Cheers.
INSERT into TABLE (column1, column2, ...) VALUES (value1, value2, ...)
Use this
if ($con->query($query) === TRUE) {
echo "Record Successfully<br>";
}
write query in this way.
$query = "INSERT INTO review (column1 , column2 , column3 , column4 , column5 , column6) VALUES ('','$name','$email','$contact','$subject','$message')";
if(isset($res)) {
//header("Location: homepage.php");
}
replace column names with your table attributes.
Hi I am using prepared statements for the first time. I have a form whose values, i am inserting in Mysql database using Mysqli prepared statements. But the problem is if user leaves an input box empty, Query doesn't insert row to the database.
Form
<form action="test.php" method="post" class="signupform">
<input type="text" Placeholder="Name" name="name" Required="required"/>
<br />
<input type="email" Placeholder="Email-id" name="email" Required="required"/>
<br />
<input type="password" Placeholder="Password" name="pass" Required="required"/>
<br />
<span>Male<input type="radio" name="sex" value="M" checked="checked"/> Female<input type="radio" name="sex" value="F"/></span>
<br />
<input type="text" Placeholder="City" name="city"/>
<br /><br />
<input type="submit" value="CREATE MY ACCOUNT" name="submit"/>
</form>
<?php
if(isset($_POST['submit'])){
include_once('includes/db.php');
$name=$_POST['name'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sex=$_POST['sex'];
$city = $_POST['city'];
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if($stmt){
echo "result inserted";
}
}
}
?>
On using above form and query when i fill all the boxes of form it insert a new row for me. But if i leave an input box empty, It doesn't insert any row.
I also have seen a lot of questions which says that if i use variables like this
if(empty($_POST['city'])) { $city = null; } else { $city = $_POST['city']; }
then it will work and most of them are accepted answers. I am confused why this solution is not working for me ???
Any help is appreciated...Thanks
Your query is wrong:
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
It should be something like:
if (!empty($name) || !empty($pass) || !empty($email))
{
$stmt = $mysqli->prepare("INSERT INTO login(`name`,`password`,`email`,`sex`,`city`) VALUES(?,?,?,?,?)");
$stmt->execute([$name, $pass, $email, $sex, $city]);
echo "result inserted";
} else {
echo 'You have not entered all of the fields.';
}
In this instance, if the variables are not empty then perform insert. Else if they are empty fire a echo stating the fields haven't been filled in.
If you are happy for the fields to be null simply change !empty() to empty() but as Fred -ii- stated above, ensure your database allows NULL within them fields.
Probably this is not one of the smartest way to do it, but hey, it will get the job done.
One of the things that you need to do before assigning a variable to an $_POST field, you need to check if that $_POST field isset and its not empty, then assign the value if not empty, Currently if someone leaves out a field in your form when you run the query you will probably get a notice of undefined.
This is what you can do.
<?php
if (isset($_POST['submit'])) {
include_once('includes/db.php');
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
$name = " ";
}
if (!empty($_POST['pass'])) {
$pass = $_POST['pass'];
} else {
$pass = " ";
}
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
$email = " ";
}
if (isset($_POST['sex'])) {
$sex = $_POST['sex'];
} else {
$sex = " ";
}
if (!empty($_POST['city'])) {
$city = $_POST['city'];
} else {
$city = " ";
}
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES(?,?,?,?,?)")) {
$stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
$stmt->execute();
if ($stmt) {
echo "result inserted";
} else {
echo "could not insert";
}
}
}
?>
There are other better ways to do this.
I have tried a number of different ways of inserting data into my DB I have got a little further it used to just say error but now when you submit the form it loads a blank page, the data from the form isn't added to the table however ;/
<form name="datainsert" method="post" action="dataInsert.php">
<label>Server Name: </label>
<input type="text" name="name" placeholder="Enter Server Name" style="margin-left:90px; width:160px; padding:5px; margin-top:10px;"><br />
<label>Server Location:</label>
<input type="text" name="location" placeholder="Enter Server Location" style="margin-left:71px; width:160px; padding:5px; margin-top:10px;"><br />
<label>Server Operating System:</label>
<input type="text" name="os" placeholder="Enter Server OS" style="margin-left:16px; width:160px; padding:5px; margin-top:10px;"><br/>
<input style="margin-top:10px;" name="submit" value="submit" type="submit">
</form>
<?php
include 'dbconnect.php';
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
)
mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
$result=mysql_query($sql);
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
?>
Can anyone see a syntax error or where I might be going wrong
thanks!
Try this. your code is Ok just comment this line ($result=mysql_query($sql);). use this code. why you try mysql_qury() two times in your code.
<?php
include 'dbconnect.php';
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
)
$result = mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
//$result=mysql_query($sql);
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
?>
You have no $sql variable and you are using it mysql_query try this,
<?php
include 'dbconnect.php';
if(isset($_POST['submit'])){ // check for form submit
$name = $_POST['name'];
$location = $_POST['location'];
$os = $_POST['os'];
$result=mysql_query("INSERT INTO fostvm (name, location, os) VALUES ('$name', '$location', '$os')");
if($result){
echo "Data Added Successfully";
} else {
echo "Error";
}
}
?>
Also you should use mysqli as mysql is deprecated