I m trying to send data value in database using ajax but it's not working. please any one help me.
I m trying to send data value in database using ajax but it's not working. please any one help me.
form.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="send_value" action="form.php" method="post">
<input type="text" name="name" value="" id="name">
<input type="text" name="address" value="" id="address">
<input type="submit" value="submit" id="save">
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function() {
var name = $('#name').val();
var address = $('#address').val();
$.ajax({
type: "POST",
cache: false,
url: 'ajax.php',
data: { name: name, address: address},
success: function(data) {
alert('data has been stored to database');
}
});
});
});
</script>
</body>
</html>
and php file
<?php
include('DataModel.php');
$con = mysqli_connect("localhost","root","","ajax_test");
if (!$con)
{
die();
}
$name = $_POST['name'];
$address = $_POST['address'];
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ($name,$address) ";
$query = mysqli_query($sql,$con);
$fetch = mysqli_fetch_assoc($query);
echo json_encode($fetch);
?>
Quotes are missing around the query
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ('$name', '$address')";
You should also use prepared statements but in the very very least please escape your strings before passing them into the query
$name = mysqli_real_escape_string($con, $_POST['name']);
$address = mysqli_real_escape_string($con, $_POST['address']);
Lest you encounter bugs with addresses or names containing single quotes or leave yourself open to SQL injection attacks.
You have forgot the quotes here
$sql = "INSERT INTO `test`(`name`, `address`) VALUES ('$name','$address') ";
Or you can bind param like this
$stmt = $mysqli->prepare("INSERT INTO `test`(`name`, `address`) VALUES (?,?)");
$stmt->bind_param('ss', $name, $address);
$stmt->execute();
Related
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 am unable to connect insert the date into sql server using angularjs & php.
I want to know how to insert data in sql and fetch the data from db.
<body>
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<input type="button" value="submit" ng-click="insertdata()"/> <br/>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular-route.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script type="text/javascript">
var app = angular.module('myapp',[]);
app.controller('empcontroller', function($scope, $http){
$scope.insertdata=function(){
$http.post("insert.php",{'emp_no':$scope.emp_no,'first_name':$scope.first_name,'last_name':$scope.last_name,'dept_name':$scope.dept_name})
.success(function(data,status,headers,config){
console.log("data insert succesfully");
});
}
});
</script>
</body>
PHP CODE:
$data = json_decode(file_get_contents("php://input"));
$empno = mysql_real_escape_string($data->emp_no);
$fname = mysql_real_escape_string($data->first_name);
$lname = mysql_real_escape_string($data->last_name);
$dept = mysql_real_escape_string($data->dept_name);
$con = mysql_connect("localhost", "root", "root");
mysql_select_db("company", $con);
mysql_query("INSERT INTO employee('emp_no', 'first_name', 'last_name', 'dept_name')VALUES('".$empno."','".$fname."','".$lname."','".$dept."')");
Here You go Try this
HTML
<div ng-app="myapp" ng-controller="empcontroller">
<form>
Employe No. <input type="text" ng-model="emp_no" /><br/>
First Name. <input type="text" ng-model="first_name" /><br/>
Last Name. <input type="text" ng-model="last_name" /><br/>
Department. <input type="text" ng-model="dept_name" /><br/>
<button ng-click="postData()">Submit</button><br>
</form>
</div>
CONTROLLER:
app.controller('empcontroller', function ($scope, $http) {
/*
* This method will be called on click event of button.
*/
$scope.postData = function () {
var request = $http({
method: "post",
url: window.location.href + "insert.php",
data: {
emp_no: $scope.emp_no,
first_name: $scope.first_name,
last_name: $scope.last_name,
dept_name: $scope.dept_name,
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
});
PHP CODE:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$emp_no = $request->emp_no;
$first_name = $request->first_name;
$last_name = $request->last_name;
$dept_name = $request->dept_name;
$servername = "localhost";
$username = "root";
$password = "root"; //Your User Password
$dbname = "myDB"; //Your Database Name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO employee (emp_no, first_name, last_name, dept_name)
VALUES ($emp_no, $first_name, $last_name , $dept_name)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Three problems with your code:
When executing $scope functions with ng-click, best practice is to pass in the variables as you use them.
Since your PHP controller is expecting JSON, you should form a JSON object and indicate it in the headers.
.success() is being deprecated. You should use the promise .then() instead.
HTML:
<!-- need to pass model in the ng-click function -->
<input type="button" value="submit" ng-click="insertdata(emp_no, first_name, last_name, dept_name)"/>
Controller:
$scope.insertata = function(empNo, firstName, lastName, deptName) {
//make json payload object
var payload = {
emp_no: empNo,
first_name: firstName,
last_name: lastName,
dept_name: deptName
};
//pass to API
$http.post('insert.php', payload, {
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).then(function(data, status, headers, config) {
//success
}, function(data, status, headers, config) {
//an error occurred
});
}
well, using the code of KKKKKKKK now you need a php code.
To retrieve information from a json file posted using post to php you should do something like this:
$json = file_get_contents('php://input');
$obj = json_decode($json); // this will retrieve the json.
And now manipulate as you want.
I have a simple 1 page webapp which uses AJAX to GET/POST mostly, however, when I try to run the SQL on one of my endpoints, it throws an internal server error and I can't think why, I tested my SQL command in PHPMyAdmin and it worked, I tested to be sure my values are being captured, and they are, so I cannot see the issue, any help would be great, here is my form:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>Add a new album</title>
</head>
<body>
<p class="yeah">Add a new album</p>
<form action="http://localhost:8000/musicOnline/assets/scripts/php/create/new/" method="post" enctype="multipart/form-data">
<input type="text" placeholder="Artist Name" name="artist" required>
<input type="text" placeholder="Album Name" name="album" required>
<input type="text" placeholder="Genre" name="genre" required>
<input type="date" placeholder="Release Date" name="release" required>
<input type="text" placeholder="Record Label" name="recordLabel" required>
<input type="text" placeholder="enter a star rating (1 - 5)" name="rating">
<input type="submit" value="submit">
</form>
</body>
</html>
My AJAX handler:
//forms that post, put, delete or get
$(document).on("submit", "form", function (e) {
e.preventDefault();
$this = $(this),
$data = $this.serializeArray(),
$method = $this.attr("method"),
$endpointURL = $this.attr("action");
$.ajax({
type: $method,
data: $data,
url: $endpointURL,
success: function (data) {
$("#content-lockup").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error: " + textStatus + ", error thrown: " + errorThrown);
}
});
return false;
});
And the endpoints code (/assets/scripts/php/create/new/):
<?php
require "http://localhost:8000/musicOnline/assets/scripts/php/dbConn/index.php";
$artist = $_POST['artist'];
$album = $_POST['album'];
$genre = $_POST['genre'];
$release = $_POST['release'];
$rating = $_POST['rating'];
$recordLabel = $_POST['recordLabel'];
try {
//prepare our statement
$preparedQuery = $conn->prepare("insert into albums (artistName, albumName, genre, releaseDate, recordLabel, rating) values ('" . $artist . "', '" . $album . "', '" . $genre . "', '" . $release . "', '" . $recordLabel . "', '" . $rating . "')");
//execute the statement
if($preparedQuery->execute()) {
echo "success";
$conn = null;
} else {
echo "nope";
$conn = null;
}
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
?>
And my db connection:
<?php
session_start();
//setup variables
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dgc_music_online";
//instantiate our PDO connection to the DB
$conn = new PDO("mysql:host=$servername;dbname=$dbname;", $username, $password);
?>
And a screenshot of the console.log that is output:
Try to change your endpoint code to follow this manual: http://php.net/manual/en/pdo.prepared-statements.php
//prepare our statement
$preparedQuery = $conn->prepare("insert into albums (artistName, albumName, genre, releaseDate, recordLabel, rating) values (?, ?, ?, ?, ?, ?)");
//execute the statement
if($preparedQuery->execute(array($artist, $album, $genre, $release, $recordLabel, $rating))) {
In case of errors like that you should always the error details in you nginx/apache error logs. Most of the time there is something helpful recorded.
I am trying to insert data into a database with ajax. The problem is that everything works excepting the insertion of data in the database.
When I click the submit button I get the proper message "You have been subscribed" just that it doesn't insert the data in the database. And don't understand exactly why.
I have dbconn.php
<?php
$db = new mysqli($dbhostname, $dbuser, $dbpass, $dbname);
if ($db->connect_errno) {
echo "Failed to connect to MySQL: (" . $db->connect_errno . ") " . $db->connect_error;
}
?>
common-functions.php
<?php
require_once('dbconn.php');
function subscribe() {
global $db;
if(isset($_POST['semail'], $_POST['sname'])) {
$name = $_POST['sname'];
$email = $_POST['semail'];
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed') VALUES ('".$db->escape_string($name)."', '".$db->escape_string($email)."', 0)");
echo "You have been subscribed";
}
}
subscribe();
?>
subscribe.php
HTML
<form name="subscribe" class="subscribe">
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
AJAX
<script type="text/javascript">
$(document).on('submit','.subscribe',function(e) {
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
alert(output);
}
});
});
</script>
Remove the quotes and substitute with backticks here
$db->query("INSERT INTO subscribers (`name`, `email`, 'confirmed')
^ ^
I made a form to insert and modify categories in my project.
when i hit "submit" i get the record submitted into the database but it appears empty !
and if i go to the databse field and write the text myself it will appear good in MySQL and and "????" in the browser !
here is the code i wrote:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('$_POST[name]','$_POST[parent_id]','$_POST[description]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<form action="ins.php" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
You have to quote (using ") around your index name in your SQL request because $_POST is an array:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST["name"]."','".$_POST["parent_id"]."','".$_POST["description"]."')";
But generally speaking please dont trust directly what's user are posting to your script to avoid SQL Injections. You can use mysqli::query which is way better and safer :
Mysqli
First sanitize your user input.
If you after that want to use the values from the array without all the concatenation everyone else mentions use {} around array accessors.
$sql="INSERT INTO categories (name, parent_id, description)
VALUES
('{$_POST['name']}','{$_POST['parent_id']}','{$_POST['description']}')";
To clean for example $_POST do something like this is a good start. This is a bit of my older code. As others have written use mysqli instead
function clean_array($t_array)
{
foreach($t_array as $key=>$value)
$array[$key] = mysql_real_escape_string( trim($value) );
return $t_array;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
if ($_POST['action']=="doformpost") {
//only do DB insert if form is actually posted
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="ins.php" method="post">
<input type="hidden" name="action" id="action" value="doformpost" />
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
Try using double quotes in your statement like this:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
lots of issues here.
$_POST[name] should be $_POST['name']
your query will run even if the form is not submitted.
you are using deprecated mysql_* functions. Use PDO or mysqli
Your code is vulnerable to sql injection
With all that out, here's what you need to do.
Just to verify that the form is submitted, use
if( !empty($_POST['name']) &&
!empty($_POST['parent_id']) &&
!empty($_POST['description']) )
(use isset if empty value is allowed.)
Then run the query.
In PDO, the code will look like this ->
<?php
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "mydb";
$dbuser = "user";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "INSERT INTO categories (name, parent_id,description)
VALUES
(?,?,?)";
$q = $conn->prepare($sql);
$q->execute(array($_POST[name],$_POST[parent_id],$_POST[description]));
?>
This is just a start. you can use try and catch block to catch exceptions.
Before running query, check if form is submitted by !empty() or isset() as described above.
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
Please provide quotes while inserting values in database
I found that if you forget the simply html attribute in the <form> for METHOD="POST"... you will get blank data in your database despite all else working fine.
ie.. <form action="file.php" method=POST>
use this statement for your code
if( isset($_POST['name']) && isset($_POST['parent_id']) && isset($_POST['description']) )
//your insert query
Don't forgot about safety!
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".mysql_real_escape_string($_POST['name'])."','".intval($_POST['parent_id'])."','".mysql_real_escape_string($_POST['description'])."')";
And i think a problem with encodings.
launch query before you inserting a data:
$sql = 'set names `utf-8`'; (for example)
Use Below insert query to insert data , i m sure it will definitely help you.
$sql="INSERT INTO categories (name,parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
Try this
<?php
if(isset($_POST['submit'])) {
$con = mysql_connect("localhost","user","pass");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description) VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
} else {
echo "1 record added";
}
mysql_close($con);
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit"name="submit" value="Submit" />
</form>
</body>
</html>
Me too faced the same problem.
Proceed your insert query like this, this helped me.
$email_id = $_POST['email_id'];
$device_id = $_POST['device_id'];
***For My Sqli***
if(!empty($email_id ))
{
$result_insert = mysqli_query($db_conn,"INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysqli_affected_rows($db_conn)>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
///////////////////////////////////////////////////////////////////////////////
**For My Sql**
if(!empty($email_id ))
{
$result_insert = mysql_query("INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysql_affected_rows()>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
NOTE : here i have checked only for email.