when echo the variable on php it works , but for insert it to database it doesn't , what is the probleme I didn't see any issue on the code , thanks for help
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send @ jquery-3.1.1.min.js:4
ajax @ jquery-3.1.1.min.js:4
(anonymous) @ jquery.PHP:26
dispatch @ jquery-3.1.1.min.js:3
q.handle @ jquery-3.1.1.min.js:3
mysqldb.php this is the php file to connect to the database
<?php
$conn = mysqli_connect('localhost', 'root', 'password' , 'database');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Try this to see the exact error:
<?php
try
{
$conn = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
}
catch(PDOException $e ){
echo "Error: ".$e;
}
.....//
The query is "well" built.
The variables there are well encapsulated.
There's some security issues that you can fix by preventing against cross site scripting (XSS) and SQL injection. This is done at the query level. There's lots of threads in Stack explaining how to do that.
Try and use mysqli in the following way:
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "your query here";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
echo $result ;
} `
Thank you for telling me to write the suggestion in an answer.
Thank you also for accepting as the right answer, that showed a lot of consideration from your side.