I've got an problem in my code. The insert is not working. The code is below.
HTML:
<form action="staff.php" method="post" class="center" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="size" value="1000000">
<input type="text" placeholder="headline of the news" name="title">
<input type="file" accept="image/*" name="image">
<select name="side" value="side">
<option>Left</option>
<option>Header</option>
<option>Main</option>
<option>Ending</option>
</select>
<textarea name="desc" id="description" cols="30" rows="10" placeholder="full news" name="desc"></textarea>
<input type="submit" name="go" value="Post">
</form>
PHP:
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase");
$charset = mysqli_set_charset($db,"utf8");
$msg = "";
if (isset($_POST['go'])) {
$target = "images/".basename($_FILES['image']['name']);
$title = $_POST['title'];
$image = $_FILES['image']['name'];
$side = $_POST['side'];
$desc = $_POST['desc'];
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('$title', '$image', '$side', '$desc')";
$result = mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "<p class='success'>Image uploaded successfully</p>";
} else {
$msg = "<p class='error'>There was a problem uploading the image</p>";
}
}
?>
Everything is fine except the inserting into database.
add concatenation in the query like this
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
Your query is fine, it should work.
But you're allowing SQL injections, so if you send within parameter single quotes your query will not work as expected and will throw out an error...
You should first:
clear passed strings (use mysqli_real_escape_string), http://php.net/manual/en/mysqli.real-escape-string.php
Check if mysqli_query executed if not then use mysqli_error to find out what error caused your query to not work: http://php.net/manual/en/mysqli.error.php
$sql = "INSERT INTO contents VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
This could be a shorter way.
Use as
<?php
$db = mysqli_connect("DB SERVER", "DB USER", "DB PASS", "DataBase") or die(mysqli_error("Could not connect to Database"));
mysqli_query($db,"SET NAMES 'utf8'");
$msg = "";
if (isset($_POST['go'])) {
$target = "images/".basename($_FILES['image']['name']);
$title = mysqli_real_escape_string($db,$_POST['title']);
$image = mysqli_real_escape_string($db,$_FILES['image']['name']);
$side = mysqli_real_escape_string($db,$_POST['side']);
$desc = mysqli_real_escape_string($db,$_POST['desc']);
$sql = "INSERT INTO contents (title, image, side, description)
VALUES ('$title', '$image', '$side', '$desc')";
$result = mysqli_query($db,$sql) or die(mysqli_error($db));
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "<p class='success'>Image uploaded successfully</p>";
}else{
$msg = "<p class='error'>There was a problem uploading the image</p>";
}
}
?>
$sql = "INSERT INTO contents (title, image, side, description) VALUES ('".$title."', '".$image."', '".$side."', '".$desc."')";
The problem is here use this.
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'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
<?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.
I want to insert and update customer data by clicking on insert and update button using functions but when I click on insert or update button no data is inserted or updated whats the problem with my code??
<form action="Customer.php" method="post">
<div>
<form>
Phone No <input type="number" placeholder="Search" name="phoneno" />
First Name <input type="text" name="FirstName" />
Last Name<input type="text" name="LastName" />
Phone No<input type="number" name="CustomerPhoneNo" />
Address<input type="text" name="Address" />
Customer ID<input type="number" name="CustomerID" />
<input type="Submit" value="Add Customer" style="font-size:20px" onClick="insert()">
<input type="Submit" value="Update Customer" style="font-size:20px" onClick="update()">
</form>
</div>
"Customer.php"
<?php
$dbhost="127.0.0.1";
$dbname="root";
$dbuser="info";
$dbpsd="";
$link = mysqli_connect("$dbhost", "$dbuser", "$dbpsd", "$dbname");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$phoneno = mysqli_real_escape_string($link, $_POST['phoneno']);
$FirstName = mysqli_real_escape_string($link, $_POST['FirstName']);
$LastName = mysqli_real_escape_string($link, $_POST['LastName']);
$CustomerPhoneNo = mysqli_real_escape_string($link, $_POST['CustomerPhoneNo']);
$Address=mysqli_real_escape_string($link, $_POST['Address']);
$CustomerID = mysqli_real_escape_string($link, $_POST['CustomerID']);
function insert(){
$sql = "INSERT INTO clientinfo(phoneno, FirstName, LastName,CustomerPhoneNo,Address,CustomerID) VALUES ('$phoneno', '$FirstName', '$LastName','$CustomerPhoneNo','$Address','$CustomerID')";
echo "<span>Data Inserted successfully...!!</span>";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
function update(){
$sql="UPDATE clientinfo SET FirstName='$FirstName', LastName='$LastName',Address='$Address',CustomerID='$CustomerID WHERE phoneno='$phoneno' ";
if (mysqli_query($link, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($link);
}
}
close connection
mysqli_close($link);
?>
you can't use onclick tag to determine of requested page PHP function .
a easy way to do it . replace below codes at the customer.php file.
Replace :
function insert()
with :
if($_POST['Submit'] == 'Add Customer')
and replace :
function update()
with :
if($_POST['Submit'] == 'Update Customer')
Try this:
Delete the second tag and put the first one in that place.
Other thing, is that you need to review the code.
Review this Tutorial
PHP Tutorial
You are calling php function like js functions. They dont work like that. Define them like -
function insert($link, $post){
$phoneno = mysqli_real_escape_string($link, $post['phoneno']);
$FirstName = mysqli_real_escape_string($link, $post['FirstName']);
$LastName = mysqli_real_escape_string($link, $post['LastName']);
$CustomerPhoneNo = mysqli_real_escape_string($link, $post['CustomerPhoneNo']);
$Address=mysqli_real_escape_string($link, $post['Address']);
$CustomerID = mysqli_real_escape_string($link, $post['CustomerID']);
$sql = "INSERT INTO clientinfo(phoneno, FirstName, LastName,CustomerPhoneNo,Address,CustomerID) VALUES ('$phoneno', '$FirstName', '$LastName','$CustomerPhoneNo','$Address','$CustomerID')";
echo "<span>Data Inserted successfully...!!</span>";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
And cal them like -
insert($link, $_POST); // if it is inserting
I have a posting script where I need to put the post in a database but I need some data from another table to put into the post table, and I do not know how to do this, here's my code.
<body>
<?php
include ("include/header.html");
include ("include/sidebar.html");
?>
<div class="container">
<?php
require_once('appvars.php');
require_once('connectvars.php');
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit'])) {
// Grab the profile data from the POST
$post1 = mysqli_real_escape_string($dbc, trim($_POST['post1']));
$error = false;
// Update the profile data in the database
if (!$error) {
if (!empty($post1)) {
// Only set the picture column if there is a new picture
if (!empty($new_picture)) {
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
}
else {
$query = "INSERT INTO `ccp2_posts` (`post`) VALUES ('$post1')";
}
mysqli_query($dbc, $query);
// Confirm success with the user
echo '<p>Your profile has been successfully updated. Would you like to view your profile?</p>';
mysqli_close($dbc);
exit();
}
else {
echo '<p class="error">You must enter all of the profile data (the picture is optional).</p>';
}
}
} // End of check for form submission
else {
$error = false;
// Grab the profile data from the database
$query = "SELECT first_name, last_name FROM ccp2_user WHERE user_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
//DO I NEED TO PUT SOMETHING HERE TO SET A VARIABLE//
//FOR THE FIRST_NAME AND LAST_NAME VALUES TO PUT IN//
//THE DATABASE?//
if (!empty($new_picture)) {
$query = "INSERT INTO `ccp2_posts` (`first_name`, `last_name`) VALUES ('$first_name', '$last_name')";
}
else {
$query = "INSERT INTO `ccp2_posts` (`first_name`, `last_name`) VALUES ('$first_name', '$last_name')";
}
mysqli_query($dbc, $query);
else {
echo '<p class="error">There was a problem accessing your profile.</p>';
}
}
mysqli_close($dbc);
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MM_MAXFILESIZE; ?>" />
<fieldset>
<legend>Personal Information</legend>
<label type="hidden" for="post1">Post:</label><br />
<textarea rows="4" name="post1" id="post1" cols="50">Post Here...</textarea><br />
</fieldset>
<input type="submit" value="Save Profile" name="submit" />
</form>
</div>
<?php
include ("include/footer.html");
?>
</body>
</html>
I need to take the first_name and last_name data from my ccp2_user table and put it in the first_name and last_name area in the ccp2_posts table. Help?
Your $row variable should have the values of first_name and last_name:
$first_name = $row['first_name'];
$last_name = $row['last_name'];