PHP and SQL one page insert into database - php

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
}

Related

php and mysql code

I have checked and rechecked my code for a tutorial that I am doing, and I still cannot figure out what is wrong with it. A bit of help would be appreciated.
I am building a page that processes the form data from another page. The part of the markup that I am having trouble with is below.
<pre>
if (isset($_POST['submit'])) {
// Process the form
$subject_id = $_GET["subject"];
$pageName = $_POST["pageName"];
$pagePosition = $_POST["pagePosition"];
$pageVisible = $_POST["pageVisible"];
$pageContent = $_POST["pageContent"];
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
redirect_to("new_page.php");
}
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , {$pageName}, {$pagePosition} ,{$pageVisible} ,{$pageContent} )";
$result = mysqli_query($connection, $query);
if ($result) {
// Success
$_SESSION["message"] = "Page created.";
redirect_to("manage_content.php");
} else {
// Failure
$_SESSION["message"] = "Page creation failed.";
redirect_to("new_page.php?subject={$subject_id}");
}
</pre>
I have checked out the page that submits to the form processing page and the form submits correctly. I've also checked all the external functions that I reference and all of them work. Additionaly, the first variable that uses the $_GET superglobal works just fine. The problem is in the query somehow not being able to pull in the 4 $_POST variables. If I substitute all the variable values with hard-code values, the query goes through fine and creates a new row in my table.
Any help with this would be appreciated, as I have checked and rechecked this so many times, and I am sure I'm missing something very small, but it's driving me crazy.
Thanks.
You're missing quotes around your string values:
$query = "INSERT INTO pages ( subject_id, menu_name, position, visible, content ) VALUES ('{$subject_id}' , '{$pageName}', {$pagePosition} ,{$pageVisible} ,'{$pageContent}' )";
This would have been obvious if you checked for errors using mysqli_error().

no results in inserting values to MySQL with AJAX

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).

Editing a form with PHP and MySQL: Best way to obtain an ID

I have a MYSQL table with edit and delete links on each row. The edit link goes to edit_patient.php which has a form (actually, a copy of the form originally used to insert patient into the database). After few tries, the script is working although I guess it could be improved (indeed, I get a notice of "Undefined index: id" when I submit the edits. The ID is passed to the edit_patient.php file through a GET procedure. Relevant code as follows:
// Check for a valid user ID, through GET or POST:
if ( (isset($_GET['id'])) && (is_numeric($_GET['id'])) ) { // From view_patient.php
$id = $_GET['id'];
} elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) { // Form submission.
$id = $_POST['id'];
} else { // No valid ID, kill the script.
echo '<p>Sorry, it is not possible to update patient info at this time</p>';
include ('../elements/layouts/footer.php');
exit();
}
And, after some clean up and check on submitted values:
if($action['result'] != 'error'){
// Make the query:
$q = "UPDATE `demographics`
SET lastname='$lastname', firstname='$firstname', clinic='$clinic', sex='$sex', dob='$dob', age='$age',
disease_1='$disease_1', disease_2='$disease_2', disease_3='$disease_3', address='$address', city='$city', country='$country',
zip='$zip', phone_1='$phone_1', phone_2='$phone_2', phone_3='$phone_3', email_1='$email_1', email_2='$email_2',
physician='$physician', notes='$notes'
WHERE dem_id=$id
LIMIT 1";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_affected_rows($db_connect) == 1) { // If it ran OK.
// Tell the user we have edited patient data successfully
$action['result'] = 'success';
array_push($text,'Patient data have been updated on databank');
}else{
$action['result'] = 'error';
array_push($text,'Patient data could not be changed on databank. Reason: ' .
'<p>' . mysqli_error($db_connect) . '<br /><br />Query: ' . $r . '</p>');
} // End of if (empty($errors)) IF.
} // End of if (empty rows))
Ok, so far so good. Now, in order to show already inserted data, I run another query:
// Retrieve the user's information:
$q = "SELECT lastname, firstname, clinic, sex, dob, age, disease_1, disease_2, disease_3, address, city, country, zip, phone_1,
phone_2, phone_3, email_1, email_2, physician, notes
FROM `demographics`
WHERE dem_id='".$_GET['id']."'";
$r = #mysqli_query ($db_connect, $q);
if (mysqli_num_rows($r) == 1) { // Valid user ID, show the form.
// Get the user's information:
$row = mysqli_fetch_assoc ($r);
// Create the form:
Here, the critical row I do not understand is WHERE dem_id='".$_GET['id']."'"; --> If I it leave as it is, the script runs almost Ok but then I get a notice of undefined index id.
However, when I replace with WHERE dem_id=$id"; as in the first query, the script gives a fatal error of undefined variable: id.
Finally, to submit the form I use the following command:
" /> that is working Ok, but it is not working when I use:
" />
Can anyone help me to understand why, and how to correct the issue, I'd rather prefer to be able to use simply $id (I believe is straight forward and simple) but for some reason is not working as expected. Finally, I would like to be able to report in the form to be edited also data inserted with radio buttons and drop-down (select) menus. Any advice on that would be greatly appreciated !
Please make sure that your specific record has been updated after the submit button in your edit_patient.php ? If it works and after next which page is display ..? Is it is Display.php (i.e. all record display page ) ? Please be specify first and i really help you to solve your query.

PHP form clears on submit and just refreshes the page (doesn't send data to Mysql)

I hope someone can help.
When I submit this script the form just refreshes and doesnt display the thankyou.php page.
Thanks for any help
include 'dbc.php';
$err = array();
if(#$_POST['doAcademic'] == 'Academic')
{
// This code filters harmful script code and escapes data of all POST data from the user submitted form.
foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}
// Automatically collects the hostname or domain like example.com)
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
These join the date fields together from the HTML
#$degree_date = date("Y-m-d", mktime(0,0,0,$dt,$mo,$yr));
#$other_degree_date = date("Y-m-d", mktime(0,0,0,$dty,$moy,$yry));
#$expd_degree_date = date("Y-m-d", mktime(0,0,0,$dti,$moi,$yri));
if(empty($err)) {
// inserts data into mysql table
$sql_insert = "INSERT into `acadmic`
(`otherapply`,`otherinstitute`,`institute`,`institute_city`,
`degree_country`, `degree_date`,`degree`,`grade`, `other_degree_institute`,
`other_degree_city`,`other_degree`, `other_degree_date`,`other_degree_grade`,
`expd_degree_institute`,`expd_degree_city`,
`expd_degree_country`, `expd_degree`,
`expd_degree_date`,`current_docyear_prog`,`current_docyear_funded`,
`prevfields`,`profexperience`
)
VALUES
('$data[otherapply]','$data[otherinstitute]','$data[institute]',
'$data[institute_city]',
'$data[degree_country]', '$degree_date', '$data[degree]', '$data[grade]',
'$data[other_degree_institute]' ,'$data[other_degree_city]', '$data[other_degree]',
'$other_degree_date', '$data[other_degree_grade]', '$data[expd_degree_institute]',
'$data[expd_degree_city]','$data[expd_degree_country]',
'$data[expd_degree]','$expd_degree_date','$data[current_docyear_prog]',
'$data[current_docyear_funded]',
'$data[prevfields]','$data[profexperience]'
)
";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
This code returns the user to the thankyou page.
header("Location: thankyou.php");
exit();
}
}
thanks in advance
I dont see any mention / loading / redirection to the thank you page in your code.
Also i would suggest your print_r your $sql_insert :
print_r($sql_insert);
on the line after the $sql_insert assignment.
You might also want to check your Database to see if the row is being inserted, if it isn't then you know what your problem is (your sql) , if it is being inserted then your problem is else where and you need to post the rest of your script.
I'm not sure if it's an error , but i see your table is spelled 'acadmic' in your sql request:
INSERT into `acadmic`
You also have a trailing , after profexperience field:
,`profexperience`,)
VALUES
Post some more details :)
After submission I think you just want to header('Location: thankyou.php'); exit;

Enter variable into sql table Problems

Ok I am having problems insert a variable into a sql table. Heres my code
if (isset ($_GET['comment']))
$commentEntered = $_GET['comment'];
else
$commentEntered = "refuse";
Above I get the variable
Then I try to pass it to the database with the code below
$sql = "insert into $DB_Table (comment) values('$commentEntered');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
My problem is, When I pass a single word it works, But when the text box where comment is received has any spaces in it, It will not insert?
i.e - The user enters Hello - This works
The user enters Hello World - This doesn't work
Any help would be much appreciated!
try
$sql = "INSERT INTO " . $table . " (comment) " .
"VALUES ('" . mysql_real_espace_string($commentEntered) . "')";
Also, dump the var $commentEntered before the "$sql = ..." line just to see what it outputs to the screen.
var_dump($commentEntered);
And another thing, try switching from GET request method to POST and grab the data from $_POST.
try to call:
mysql_query("COMMIT");
before closing the connection.

Categories