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());
}
?>
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.
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;
}
.....//
Related
I have created a html page that ask to enter quantity of items to buy and the total quantity will be calculated. I am able to send the values of the quantity of EACH item to the database since they are text field but I am not able to send the paragraph (innerHTML) value into database. How am I able to solve this please?
This is the HTML code.
<body>
<form id="Orders" method = "POST"/>
Shirts ($1 Each) :
<input id="Shirts" type="text" name="Shirts" value=""/>
Pants ($2 Each) :
<input id="Pants" type="text" name="Pants" value=""/>
Quantity:
<p id="quantity" name ="quantity" value=""/></p>
<input type="submit" class="button" id="submit" value="Order"/>
<script>
$('#submit').on('click',function(e){
$.ajax({
type: "POST",
url: 'orders.php',
data: $("#Orders").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
</script>
This is the javascript.
var Shirts = document.getElementById("Shirts").value;
var Pants = document.getElementById("Pants").value;
var Quantity = +Shirts + +Pants;
document.getElementById("quantity").innerHTML=Quantity;
This is the php code
<?php
$servername = "localhost";
$username = "Hello";
$password = "Test";
$dbname = "Test";
if(isset($_POST["Shirts"]) && isset($_POST["Pants"]) && isset($_POST ["quantity"]))
{
$shirts = $_POST["Shirts"];
$pants = $_POST["Pants"];
$quantity = $_POST["quantity"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO Test (Shirts, Pants, Quantity) VALUES ('$shirts','$pants','$quantity')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Failed " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
I am trying to retrieve data from database using AJAX without any success. These are the codes I am using. I dont see any specific errors in console.
HTML:
<button type="button" name="result_submit" id="result_submit" >Submit</button>
<div class="result" id="result" name="result"> </div>
Jquery:
$(document).ready(function(e) {
$('#result_submit').click(function() {
$.ajax({
url :"Income.php",
type :'POST',
success: function(data){
$("#result").html(data);
}
});
});
});
Income.php content:
<?php
include_once 'dbConnection.php';
$stmt = mysqli_stmt_init($conn);
$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
if(!mysqli_stmt_prepare($stmt,$income))
{
$message = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
}
else
{
mysqli_stmt_execute($stmt);
$result= mysqli_stmt_get_result($stmt);
$income_sum=mysqli_fetch_assoc($result);
$TotIncome= "Total Income is ".$income_sum['incomeNumber'];
}
?>
dbConnection.php has connections details:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "wordpress";
$conn= mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
?>
Can someone guide me how to resolve the issue
You need to echo your data from your PHP file :
$income = "select SUM(amount) as incomeNumber FROM wp_formdata WHERE entry_type='Income'";
$response = '';
if (! mysqli_stmt_prepare($stmt,$income)) {
$response = '<h1 style="color:red;padding-top:5%;">SQL Error !!</h1>';
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$income_sum = mysqli_fetch_assoc($result);
$response = "Total Income is ".$income_sum['incomeNumber'];
}
echo $response;
First off all add on the beginig of page:
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('error_reporting', E_ALL);
and
printf("Errormessage: %s\n", mysqli_error($income_sum));
afther query to db.
Do you have any respons from the page called by ajax?
The script that you call using AJAX doesn't render anything.
echo $TotIncome;
After i searched for this solution on this site, nothing i found. Here is basic php code, just for testing.
index.php
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data)
{
//alert(data);
window.location.reload();
}
});
});
});
</script>
qry.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if($_REQUEST['chk'] == true){
$stok = '1';
}
elseif ($_REQUEST['chk'] == false) {
$stok = '0';
}
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
How to set checkbox checked true or false into mysql and then echo if in html? It's always set to 0 in mysql boolen.
<input type="hidden" name="chk" id="chk" value="1" <?php if ($checked == '1') {echo 'checked';} else {} ?>/>
I tried everything from this site and nothing works.
Try this Jquery. This will get rid of the always value 1 problem you're having. What this code does is when you click on the "submit" button it check the status of your check box. If the check box is checked then the code will take the checked check box value and send that in the ajax function if it's not checked then the value 0 get assigned and that will be sent using the ajax.
Doing this will reduce the work has to be done by the back end PHP. I also made some changes to your PHP code as well.
$(document).ready(function() {
$(document).on('click', '#submit', function() {
if ($("#chk").is(":checked")) {
var chk = $('#chk').val();
}else{
chk = 0;
}
$.ajax({
url: "qry.php",
method: "POST",
data: {
check: chk
},
success: function(data) {
//alert(data);
window.location.reload();
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
You will see that the way I'm inserting the data is a bit different from the way you have done. I'm using mysqli_ prepared statements which makes SQL injection a hard to do.
$query = $connect -> prepare("INSERT INTO test(checked) VALUES (?)";
$query -> bind_param("i", $_REQUEST['check']);
if ($query -> execute()) {
echo "Zahtev je uspešno poslat!";
} else {
echo "Error: " . $query . "<br>" . $connect->error;
}
jsFiddle if you want to test it.
You write the value into check, but read it back from $_REQUEST['chk']. That won't work. Change that to $_REQUEST['check'].
You are using val() to get the state of the checkbox, you should use checked.
Also, you are possibly open to SQL injection, start using prepared statements.
Add another line while sending the AJAX request.
While sending the value of checkbox, send 1 or 0.
It will reduce our work at PHP end.
So, the code should be:
var check = $('#chk').is(":checked");
check = (check) ? 1 : 0;
Final code should be:
<input type="checkbox" name="chk" id="chk" value="1" />
<button type="button" name="" id="submit">TEST</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var check = $('#chk').val();
check = (check) ? 1 : 0;
$.ajax({
url:"qry.php",
method:"POST",
data: {check:check},
success:function(data) {
//alert(data);
window.location.reload();
}
});
});
});
</script>
And PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "check";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
$stok = $_REQUEST['chk'];
$query = "INSERT INTO test(checked) VALUES('$stok')";
$result = mysqli_query($connect, $query);
if ($result === TRUE) {
echo "Zahtev je uspešno poslat!";
}
else {
echo "Error: " . $query . "<br>" . $connect->error;
}
?>
I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});
So I need simple thing, I need to create button in my website, after button is clicked, It should truncate database table, but I can't do It successfully by myself. So could you help me, please?
Here I'm trying to creeate button:
<input type="button" id='delete' class='delete' value='Truncate' onClick="$truncate">
</input>
I know this is wrong way to use PHP variable in HTML, but I don't know how to do It correctly.
Here is my PHP variable:
$truncate= "TRUNCATE TABLE myTable";
With connection to database is all right:
$mysqli = new mysqli("localhost","database","password","asd");
So maybe here is better method to create button for truncate database's table? Thank you.
UPDATED:
This won't work too, nothing happens after button is clicked.
if(isset($_POST['delete'])){
$delete= "TRUNCATE TABLE myTable";
}
?>
<input type="button" id='delete' class='delete' name="delete" value='Truncate' onClick="delete">
</input>
Here, give this a try.
PHP (delete_table.php)
<?php
// CONNECT TO THE DATABASE
$DB_HOST = "your_host";
$DB_NAME = "your_DB_name";
$DB_USER = "username";
$DB_PASS = "password";
$dbc = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME)
or die('Error connecting to MySQL server');
if(isset($_POST['delete'])){
$query = "TRUNCATE TABLE `yourTable` "; // replace yourTable with one to delete
$result = mysqli_query($dbc,$query)
or die('Error deleting table.');
}
else {
echo "Sorry";
}
?>
HTML form
<form method="post" action="delete_table.php">
<input type="submit" id='delete' class='delete' name="delete" value='Truncate'></input>
</form>
I'm by far no jQuery expert but maybe something like this....untested of course
jQuery
$(document).ready(function() {
$('#delete').click(function() {
var table = $('#table').val(); //where #table could be an input with the name of the table you want to truncate
$.ajax({
type: "POST",
url: "truncate.php",
data: 'table='+ table,
cache: false,
success: function(response) {
alert('table dropped');
},
error: function(xhr, textStatus, errorThrown) {
alert('request failed');
}
});
});
});
PHP (truncate.php)
try {
// create a new instance of a PDO connection
$db = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
$table = $_POST['table'];
$sql = 'TRUNCATE TABLE '.$mytable;
$stmt = $db->prepare($sql);
$stmt->execute();
?>