on my research site, I have a few radio buttons and I want to send their values to MySQL table using jquery and AJAX. All buttons and jquery code are put in single-project.php (I modified WordPress theme) and the bits of code that should handle interaction with the MySQL are put in the db.php in the same folder.
However, something is not in order, because values do not appear on the database table. Could someone help?
jquery:
//the last button
$('#submit_last_button').click(function(){
SomeVariable = $('input:radio[name=lastRadio]:checked').val();
if (!$("input:radio[name=lastRadio]").is(":checked")) {
$("label#lastRadio_error").show();
$("input#lastRadio").focus();
return false;
} else {
if ('input:radio[name=lastRadio]:checked')
$('#PreviousButtonDiv').hide();
$('#NextDiv').show();
$.post('db.php',{action: "submit_last_button", previous_variable:SomePreviousVariable, last_variable:SomeVariable},function(res){
$('#result').html(res);
});
}
});
});
db.php:
<?php
$con = mysql_connect('localhost','user', 'password');
$db = mysql_select_db('my_database');
if($_POST['action'] == 'submit_last_button'){
$previous_variable = mysql_real_escape_string($_POST['previous_variable']);
$last_variable = mysql_real_escape_string($_POST['last_variable']);
$sql = "insert into MyTable (id, variable1, variable2) values ( NULL, '$previous_variable', '$last_variable')";
$query = mysql_query($sql);
if($query){
echo "Record Inserted.";
}else {
echo "Something Wrong!";
}
}
?>
There are various possibilities of what is not working on your code. But first, the problem is not in AJAX not saving on MySQL. AJAX is passing your data to the php script on your server to then, save it on MySQL.
Check if the values are reaching your script correctly;
Check if you're getting a db connection - check error logs or print them out;
Check if you're not getting a SQL syntax erro - again, check for logs;
Check if auto-commit is true (it is by default).
Related
[ASK] I make a quiz that require a result that can be save to my database
oke here the code that i tried to save the result from that quiz
$scope.questions.forEach(function (q, index) {
answers.push({ 'QuizId': $scope.quiz.Id, 'QuestionId': q.Id, 'Answered': q.Answered });
$http.post('http://localhost/server_log/insert.php', answers).success(function (data) { alert(data);
});
});
and here is the insert.php
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
$connect = mysqli_connect("localhost", "root", "", "dataujian");
$data = json_decode(file_get_contents("php://input"));
$answer = mysqli_real_escape_string($connect, $data->Answered);
$query = "INSERT INTO nilai (jawaban) VALUES ('$answer')";
mysqli_query($connect, $query);
echo true;
?>
But when i try to submit it nothing happen, it there anything wrong with my code.
it there anything wrong with my code.
There are a few problems with your code. Build in small pieces so you can test as you go.
One problem is that you're doing a new HTTP POST request for each answer.
Another problem is that you're not validating your inputs on the PHP side, so you don't know what php://input actually contains or whether json_decode was successful
Another problem is that you're not checking for errors when you run your DB query so you have no clue whether the query was executed successfully
You say:
when i try to submit it nothing happen
This is vague. Does it mean that AngularJS doesn't make any request? That PHP doesn't respond?
I have written a PHP page with a form on the submit button I set the action to the PHP form page.
<form id="form1" method="post" action="../control_lbs/lbs_trace.php">
The INSERT INTO is basic sql load information to the database.
The problem i have every time I open the page it sends blank information to the rows. Is there away I can prevent this from happening?
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req,
lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES
('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]'
,'$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
The above is my PHP action code
This is the new code and full code I use
if ($con = mysql_connect($host, $username, $password)) {
if ( !empty($_POST["send"])) {
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES ('$_POST[lbs_msisdn]','$_POST[lbs_req_by]','$_POST[lbs_date_req]','$_POST[lbs_reason]','$_POST[lbs_station]','$_POST[lbs_cas]','$_POST[lbs_traced_by]')";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
On refresh or page entry it still gives me blank info on Database
You need to use isset() to see if the $_POST variables are set. I've use $_POST in the example below, I suggest you give the submitbutton a name (like example) and use isset($_POST['example']):
if( isset($_POST) ){
$sql = "INSERT INTO lbs_trace_etrack (lbs_msisdn, lbs_req_by, lbs_date_req, lbs_reason, lbs_station, lbs_cas, lbs_traced_by)
VALUES(
'".$_POST['lbs_msisdn']."',
'".$_POST['lbs_req_by']."',
'".$_POST['lbs_date_req']."',
'".$_POST['lbs_reason']."',
'".$_POST['lbs_station']."',
'".$_POST['lbs_cas']."',
'".$_POST['lbs_traced_by']."'
)";
echo $sql; // echo it to see if it has any values
// print_r($_POST); // in case the query is still empty, uncomment this. It will show you the values in the POST array
}
I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>
Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());
store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());
For example I am a user and I want to post a comment and after submitting it and saved to my database. The other page of the admin updates and automatically the data that I inserted displays without refreshing the page of the admin. Help please..
any code can help. Thanks. I'm using php for server-side language. Any language can help javascript or ajax.
Javascript (jQuery):
$.post('path_to_your_php_script.php', function(data) {
$('the_dom_element_you_want_to_show_the_comment_in').html(data);
});
Somewhere in path_to_your_php_script.php:
// some code to save the data
echo '<div>New comment</div>';
exit;
For more information, please refer to jQuery's post and ajax methods. You can do the same thing without jQuery, but you shouldn't reinvent the wheel.
yourphpfile.php is the php file where you need to do all your database operations (in your case its insert into database).
So,basically you want to show the recently insert data in a webpage without refreshing the page, to do that, we need Ajax.
So, do your insert operation in yourphpfile.php, and if the insert operation is successful, just return the result (inserted data into DB) using echo $output;exit;
where $output = 'recently inserted data';
That's what you need to do in the php side.
Your yourphpfile.php:
<?php
//your database insert operation
echo $output;// $output should have the inserted data
exit;
?>
Now in ajax function:
You could use jquery.ajax
$.ajax({
type: "GET",
url: "yourphpfile.php",
success: function(response){
if(response != '') {
//data that I inserted displays without refreshing the page of the admin
$('yourDivContent').html(response);
} else {
// response error
}
}
});
In the reponse variable you would get what you have echoed in the yourphpfile.php.
That is $output. Then you could use the reponse varible inside ajax function and use it to insert into your HTML.
Suppose you have a form and you can use Ajax for sending the data to the backend. The ajax call would look in the following way:
var id = $(this).attr('id');
$.ajax({
type:"POST",
url:"ajax.php",
data:{id:id},
success:function(data){
// do something if insertion into database has succeeded
}
});
...and in php you write something as:
// Connecting to Database
mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASS) or die ('Can not connect to MySQL database');
// Selecting Database
mysql_select_db(DBNAME) or die ('Cant select Database');
$action = mysql_real_escape_string($_POST['action']);
if ($action == "insert")
{
foreach ($recordArray as $key=>$value) {
$query = "INSERT INTO `TABLE`
SET name = `".$_POST['name']."`
SET age = `".$_POST['age']."`
.
.
mysql_query($query) or die('Error, insert query failed');
}
First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}