How to update MySql Database in Netbeans IDE 8.1 using jsp? - java

I am trying to make a registration page with around 10 details. But in no way am I able to update the database with those details. I have followed every procedure i found on every site including stackoverflow but still whenever i submit my form nothing happens. Like when i press the submit button it goes to another page and the address bar shows everything correctly but yet i don't know why there is no change in the database. I am new to JSP and Netbeans, so i am not really aware of all the things.
I used this as my guide http://www.studytonight.com/servlet/registration-form-example-in-servlet.php
P.S. I am new to JSP and netbeans, so i am not aware of a lot of things. Thanks in advance.

First Create a class like this
class DBController {
private $host = "Your IP";
private $user = "User Name";
private $password = "Password";
private $database = "Your Database";
function connectDB() {
$conn = mysql_connect($this->host,$this->user,$this->password);
return $conn;
}
function insertQuery($query) {
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
} else {
return $result;
}
}
}
?>
Create a text box
<input type="text" class="" name="patfirstname" value="<?php if(isset($_POST['patfirstname'])) echo $_POST['patfirstname']; ?>">
And a submit button
<input type="submit" name="submit" value="Submit" />
And in the same registration form create a post PHP function
<?php
if(isset($_POST['submit'])== "POST")
{
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO new_table ( Name ) VALUES ( '" . $_POST["patfirstname"] . "');";
$result = $db_handle->insertQuery($query);
}
?>
Hope this helps..

Related

Edit drop--down list when modifying in codeigniter

help! I have two drop-down lists in which the comunas drop-down list is ciudades dependent, it works perfect. The problem comes when I need to bring the drop-down lists with the saved data to modify them. It will only get me to bring what is selected in the list of ciudades, but in the comunas it will not be able to achieve it.
Is there any way to do this? I have become somewhat confused.
This is my code!
<!-- language: lang-or-tag-here -->
THIS IS THE VIEW CODE
<label>Ciudad:</label><select id="idciudad" name="idciudad" required autocomplete="off">
<option value="0">Seleccione</option>
<?php foreach($listaciudades as $ciudad):?>
<option value="<?= $ciudad['idciudad']?>"
<?php if ($idciudad == $ciudad['idciudad']) : ?> selected<?php endif; ?>
>
<?= $ciudad['nombre']?>
</option>
<?php endforeach; ?>
</select>
<label>Comuna:</label> <select id="idcomuna" name="idcomuna">
<option value="0">Comuna</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
$("#idciudad").change(function() {
$("#idciudad option:selected").each(function() {
idciudad = $('#idciudad').val();
$.post("<?php echo base_url(); ?>index.php/clientes/fillCiudades", {
idciudad : idciudad
}, function(data) {
$("#idcomuna").html(data);
});
});
});
});
</script>
THIS IS THE CONTROLLER CODE
public function fillCiudades() {
$idciudad = $this->input->post('idciudad');
if($idciudad){
$this->load->model('ClientesModel');
$comuna = $this->ClientesModel->getCiudades($idciudad);
echo '<option value="0">Comunas</option>';
foreach($comuna as $fila){
echo '<option value="'. $fila->idcomuna .'">'. $fila->nombre .'</option>';
}
} else {
echo '<option value="0">Comunas</option>';
}
}
First of all, you need to parse a variable with the saved idcomuna from the controller to the view, as you do with the saved idciudad. To do that, you must edit the code of the function that loads the view (you didn't include it on your question).
It would be something like (this code is for guidance only):
public function thefunctionthatloadstheview($idcliente) {
// The rest of your code here...
// I supposed you get the client data from database using a model, something like this...
$this->load->model('ClientesModel');
$cliente = $this->ClientesModel->getCliente($idcliente);
$your_view_data = array(
'idciudad' => $cliente->idciudad,
'idcomuna' => $cliente->idcomuna,
// The rest of the data like $listaciudades, etc...
);
$this->load->view('your_view', $your_view_data);
}
Once you have parsed the $idcomuna as you did with $idciudad, you must make two other changes in your view and the fillCiudades function.
The items of the second dropdown only load when the first one changes. To make it load when the page does, modify the Javascript:
<script type="text/javascript">
// Create a function to make POST request, parsing the value of the first dropdown (ciudades) and the saved value of idcomuna...
function fillCiudades_js() {
$.post("<?php echo base_url(); ?>index.php/clientes/fillCiudades", {
idciudad: $('#idciudad').val(),
idcomuna: <?php echo $idcomuna; ?>
}, function(data) {
$("#idcomuna").html(data);
});
}
$(document).ready(function() {
// Make a request when the page is ready...
fillCiudades_js();
// Make a request while the first dropdown changes...
$("#idciudad").on("change", fillCiudades_js());
});
</script>
Then, modify the fillCiudades function to get the value of idcomuna parsed through the Javascript code:
public function fillCiudades() {
$idciudad = $this->input->post('idciudad');
$idcomuna = $this->input->post('idcomuna');
if ($idciudad) {
$this->load->model('ClientesModel');
$comuna = $this->ClientesModel->getCiudades($idciudad);
echo '<option value="0">Comunas</option>';
foreach ($comuna as $fila) {
echo '<option value="'. $fila->idcomuna .'"' . ($idcomuna == $fila->idcomuna ? 'selected' : '') . '>'. $fila->nombre .'</option>';
}
} else {
echo '<option value="0">Comunas</option>';
}
}
With those changes, the second dropdown should be loaded with the saved value selected by default.
P.S. I couldn't test the code, so it's possible that there is some small error... but I hope it helps!

Mail script needs running every hour, but cron not working

Below is the fully functioning code. It works when I call it via the browser. However, I can't get my Cron job to run it. I have tried coming up with any solution and am open to any ideas that will make this script fire off once every hour 24/7 365 so to speak.
Info:
Hostgator
PHP 5.4
Link for Hostgator Cron commands: http://support.hostgator.com/articles/cpanel/what-do-i-put-for-the-cron-job-command?utm_source=cPanel&utm_medium=message&utm_campaign=Cron%20Jobs
I have tried the following:
When doing any of these I have yet to have it add a sale to the database or send a single email:
/opt/php54/bin/php /home1/user/public_html/Sales/scripts/sales-notif_em.php - Could not open input file: /home1/user/public_html/scripts/sales-notif_em.php
php /home1/user/public_html/Sales/scripts/sales-notif_em.php - blank email with nothing but this showing: Content-type: text/html
php -q /home1/lotscav1/public_html/Sales/scripts/sales_notif_em.php - I don't get any emails from the system of course
/usr/bin/curl home1/user/public_html/scripts/sales-notif_em.php - curl: (3) malformed
any command (like php or /usr/bin/curl) that has the second half with http://website.c0m/Sales/scripts/sales_notif_em.php - causes a JSON Error when trying to add the Cron job
I have checked the following things:
File permissions are 655
Timestamp is less than an hour old under the customers table
Here is my code:
<?php
//find out current time and 1 hour ago
date_default_timezone_set('America/New_York');
$current_time = strtotime("now");
$hour_ago = strtotime('-1 hour');
//////////////////////////////////////////////////////////////////
/////////////////l// Connect to Sales Database ///////////////////
//////////////////////////////////////////////////////////////////
$mysqli_s = new mysqli("localhost", "user", "password",
"server_sales_data");
if ($mysqli_s->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli_s->connect_errno . ")
" . $mysqli_s->connect_error;
}
//////////////////////////////////////////////////////////////////
///////////////////// Connect to EM Database ////////////////////
//////////////////////////////////////////////////////////////////
$mysqli_em = new mysqli("localhost", "user", "password",
"server_dlgEM");
if ($mysqli_em->connect_errno) {
echo "Failed to connect to MySQL_EM: (" . $mysqli_em->connect_errno .
") " . $mysqli_em->connect_error;
}
//Grab store name
$dlg_store = "EM";
$em_request = "SELECT * FROM customers WHERE date BETWEEN '$hour_ago'
AND '$current_time'";
$em_result = mysqli_query($mysqli_em, $em_request) or die("Error No
Sales EM");
while ($em_row = mysqli_fetch_array($em_result)) {
$em_prod_num = $em_row["prod_num"];
$em_receipt = $em_row["receipt"];
//////////////////////////////////////////////////////////////////
///////////////////// Grab info for EM Sales ////////////////////
//////////////////////////////////////////////////////////////////
$request_s = "SELECT * FROM all_products WHERE
dlgprod_num='$em_prod_num' AND dlg_store='$dlg_store'";
$result_s = mysqli_query($mysqli_s, $request_s) or die("Error dlg
prod num EM");
while ($row_s = mysqli_fetch_array($result_s)) {
$sku_s = $row_s["sku"];
$dlgprod_num_s = $row_s["dlgprod_num"];
$book_title_s = addslashes($row_s["book_title"]);
$dlgprod_price_s = $row_s["dlgprod_price"];
$author_name_s = addslashes($row_s["author_name"]);
$author_email_s = $row_s["author_email"];
$publisher_s = $row_s["publisher"];
$dlg_store_s = $row_s["dlg_store"];
$add_sql_s = "INSERT INTO all_author_sales SET
`sku`='$sku_s',
`dlgprod_num`='$dlgprod_num_s',
`dlgprod_nam`='$book_title_s',
`dlgprod_price`='$dlgprod_price_s',
`author_name`='$author_name_s',
`author_email`='$author_email_s',
`publisher`='$publisher_s',
`dlg_store`='$dlg_store_s',
`dlgcustomer_receipt`='$em_receipt' ";
//create signature
$sig = "The Admin Team at www.website.com";
//to
$admin_email = "admin#website.com";
$to = array($author_email_s, $admin_email);
//setup email headers
$headers='From: ' . $admin_email . "\r\n" .
'Reply-To: ' . $admin_email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= $emailbody."\n\n";
//email subject and body
$subject = "Your book stats";
$message = "
Hi $author_name_s,<br />
I just wanted to send you a message and let you know that the book or
books below have just been purchased.<br /><br />
Store: $dlg_store_s<br />
Receipt: $em_receipt<br />
Sku Number: $sku_s<br /><br />
Book Title: $book_title_s<br />
Publisher: $publisher_s<br />
Product Number: $dlgprod_num_s<br />
Price: $dlgprod_price_s<br /><br />
Sincerely,<br />
$sig<br /><br />
To remove yourself from this notification, please send an email to
$admin_email with Unsubscribe in the subject line.
";
if ($mysqli_s->multi_query($add_sql_s) === TRUE) {
mail (implode(',', $to), $subject, $message, $headers);
} else {
echo "Error: " . $add_sql_s . "<br>" . $mysqli_s-
>error . "<br>" . $string;
}
}
}
?>
My bet is with wrong path to the php file you want to execute.
Try using terminal if you can, navigate to the folder where the file is placed and try running it from there via command line.
Also mind You are refering to two different names: sales-notif_em.php & sales-notif_me.php.
(Posted on behalf of the OP).
Thank you for all your help. I made a custom product with my email as the author for testing purposes. In the customers table I inserted products 111111 and 111110. However, in all_products I gave products 11111111 and 11111110. tHE end result is I made a mistake.
I hope you are able to learn something from this event. Knowledge is more important than my ego. Thank you!

How to create directory on server for user when they register?

Like the question states, I would like to create a new directory in the "Users" folder on the server when a user registers their account.
PHP:
$username = $_POST['username'];//STRING
$username = strip_tags($_POST['username']);
$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($conn,$_POST['username']);
etc.
etc.
$sql = "INSERT INTO tbl_users
VALUES ('$username', '$password', '$countryCode','$mobileNumber','$email','$profilePicture','$fname','$mname','$lname','$gender','$birthday','$occupation','$signupdate',0)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully in tbl_users";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
I'm quite new to php and I don't really understand how most of the commands work.
I am making an app in java and I want the onClick to add data to a database as well as create the following file hierarchy:
Users(Already there)
Username(Of user registering)
Media
Pictures
Videos
Audio
To add a directory in "Users" folder,You can add this code:
mkdir("Users/new_folder",0755);

How to call action with parameters of JSP Servlet from JavaScript?

function printthis()
{
var content_vlue = document.getElementById('print_content').innerHTML;
var target= 'printValue?value1='+content_vlue;
document.forms[0].action = target;
document.forms[0].submit();
}
<div id="print_content">hello i am good</div>
For frontend I am using JSP. While executing this code to get the value in servlet
String msg = request.getParameter("value1");
While executing this code the browser url changes to printValue?
But I am unable to get the value of value1
Please suggest me...
Seems you are missing value1='+content_vlue from the request
try this and see
var target= "'printValue?value1="+content_vlue+"'";
Create a hidden variable inside your form like this
<form ..>
....
<input type="hidden" id="value1" name="value1"/>
</form>
and modify javascript function to this .
function printthis()
{
var content_vlue = document.getElementById('print_content').innerHTML;
document.getElementById('value1').value = content_value;
var target= 'printValue';
document.forms[0].action = target;
document.forms[0].submit();
}
Hope this will work for you.

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

Categories

Resources