I'm trying to build a very simple "budget" website solely for practice, but I can't make this site update my database.
Basically I have a database 'budgetdb' running in XAMPP with MySQL. I've got 1 table where the structure looks like this:
I've got two files, 'index.html' and 'handleUserInput.php'.
Index.html:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var xmlhttp = new XMLHttpRequest();
var url = "handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url);
xmlhttp.send();
}
</script>
</body>
</html>
handleUserInput.php:
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$query = 'INSERT into budget VALUES ($description, $budgetin, $budgetout)';
mysql_query($query)
?>
The message prompt is displayed, but no data is shown in the database. Any clue on what I am doing wrong here?
UPDATE chrome error:
Notice: Undefined index: description in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 13
Notice: Undefined index: budgetin in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 14
Notice: Undefined index: budgetout in /Applications/XAMPP/xamppfiles/htdocs/handleUserInput.php on line 15
Other answers have shown the problem with the way you write the query, it. should be, with quotes around each of the values.
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
But you also have a problem with the way you create the URL. Quotes shouldn't be put around query parameters, and you should use encodeURIComponent to ensure that special characters are escaped properly.
var url = "handleUserInput.php?description=" + encodeURIComponent(description) + "&budgetin=" + encodeURIComponent(budgetin) + "&budgetout=" + encodeURIComponent(budgetout);
And to prevent SQL injection problems, you need to escape the strings before you use them as SQL parameters. And since you're sending the parameters in the URL, rather than in the POST data, you need to get them from $_GET, not $_POST.
$description = mysql_real_escape_string($_GET['description']);
Although if you're first learning PHP now, you should use PDO or mysqli, instead of the obsolete mysql extension, and use prepared statements instead of string substitution.
Change the line that performs the query to:
mysql_query($query) or die(mysql_error());
If there's a problem performing the query, this will display the error message.
The quotes in your query are incorrect. Should be (note outer double quotes and inner single quotes):
$query= "INSERT into budget VALUES('$description',$budgetin,$budgetout)";
However, be aware this has opened you up to a SQL injection where description is
'); DROP budget;
Also, your description may contain punctuation and spaces, which may be messing up your url. You are sending a POST anyway, so all the data should be in the body of the request not the url.
Use
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";
description is string type in database so you close with single quote or double quote in PHP String.
Always consider safety. ReWrite a code as (somewhat safety):
$description = mysql_real_escape_string( $_POST['description'] );
$budgetin = intval( $_POST['budgetin'] );
$budgetout = intval( $_POST['budgetout'] );
$query = 'INSERT into budget VALUES ("$description", $budgetin, $budgetout)';
Note: Don't use mysql_* function. It is deprecated in future versions. Use MySQLi or PDO
You are sending your values as GET parameters not POST parameters.
handleUserInput.php?description='" + description + "'&budgetin='" + budgetin + "'&budgetout='" + budgetout + "'"
Everything you pass to PHP thru url will fall into $_GET variable. Not only PHP bu every server side language will behave the same, once it is a standard GET means URL parameters and POST is Request Payload
You can change $_POST to $_GET or add your data do xmlhttprequest object
<!DOCTYPE html>
<html>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = document.getElementById('description').value;
var budgetin = document.getElementById('budgetin').value;
var budgetout = document.getElementById('budgetout').value;
var params = "description=" + description + "&budgetin=" + budgetin + "&budgetout=" + budgetout;
var xmlhttp = new XMLHttpRequest();
xmlhttp .setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp .setRequestHeader("Content-length", params.length);
xmlhttp .setRequestHeader("Connection", "close");
var url = "handleUserInput.php?";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('Variables sent to server!');
}
}
xmlhttp.open("POST", url,true);
xmlhttp.send(params);
}
</script>
</body>
</html>
In order to minize your code use Jquery library instead of simple JS code
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<input type="text" id="description">
<input type="number" id="budgetin">
<input type="number" id="budgetout">
<button type="button" onclick="updateDB()">Add to database</button>
<script>
function updateDB() {
var description = $('#description');
var budgetin = $('#budgetin');
var budgetout = $('#budgetout');
$.post( "handleUserInput.php", { "description": description, "budgetin": budgetin, "budgetout": budgetout }, function( data ) {
alert( "Variables sent to server!" );
} );
}
</script>
</body>
</html>
Use mysql_real_escape_string in order to avoid SQL injection into your application. Initial problem was caused because php variables wasn't correctly added in the string of SQL query, for example :
$input = 'aaa';
echo 'text $input';
this code will output
text $input
but this one
$input = 'aaa';
echo "text $input";
or this one
$input = 'aaa';
echo "text ".$input.";
will output
text aaa
Please check the code bellow
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "budgetdb"
mysql_connect($host, $username, $password;
mysql_select_db($dbname);
$description = $_POST['description'];
$budgetin = $_POST['budgetin'];
$budgetout = $_POST['budgetout'];
$description = mysql_real_escape_string($description);
$budgetin= mysql_real_escape_string($budgetin);
$budgetout= mysql_real_escape_string($budgetout);
$query = "INSERT into budget VALUES ('".$description."', ".$budgetin.", ".$budgetout.")";
mysql_query($query)
?>
Use single inverted comma with php variables like below.
$query = "INSERT into budget VALUES ('$description', $budgetin, $budgetout)";
Related
I have a form in LDAP where i can add a user and a password, what can i do to have a live check of the username using php and ajax, is not mysql and i don't know how to compare and switch commands like sqlquery or sql_num_rows used in mysql and move it to LDAP, i read LDAP manual on php and is different than mysql how can i replace this commands in LDAP so i can have my username checked live?? using javascript (everything uspposed to be in one page)
http://www.developphp.com/video/PHP/Check-User-Sign-Up-Name-Ajax-PHP-Social-Network-Tutorial
https://www.webslesson.info/2016/02/how-to-check-username-availability-in.html
and other web pages tried and working with mysql
i used ldap_connect, ldap_bind_ ldap_search, ldap get entries and is working printing out everythng in funny way, so using php i cleaned out everything and is printing in a nice manner everything, my question is how can i check live the username??? Like is happening (tested) i this link above???
<label for="name"><b>name</b></label>
<input type="text" name="name" onBlur="checkusername() "maxlength="15"value="">
<span id="namestatus"></span>
<script>
function checkusername(){
var status = document.getElementById("namestatus");
var u = document.getElementById("name").value;
if(u != ""){
status.innerHTML = 'checking...';
var hr = new XMLHttpRequest();
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
status.innerHTML = hr.responseText;
}
}
var v = "name="+u;
hr.send(v);
}
}
</script>
$user = 'cn=Manager,dc=mydc ,dc=it';
$password = 'mypass';
$host = 'my_numeric_IP';
$basedn = 'ou=sistem,ou=thinks,dc=mydc,dc=it';
$ds = ldap_connect("ldap://{$host}") or die('Could not connect to LDAP server.');
if($ldapbind){
$filter='(&(objectClass=inetOrgPerson)(uid=*))'; // single filter
$attributes=array('dn','uid','sn', 'displayName');
$search = ldap_search($ds,$basedn,$filter,$attributes); // search
ldap_sort($ds, $search, 'sn');
print_r($info = ldap_get_entries($ds, $search));
$info = ldap_get_entries($ds, $search);
$ldaprecord['cn'] = $_POST['name'];
$_dn = "uid=".$_POST[value'].",ou=".$_POST['othervalue'].",ou=VOIP,ou=sistem,dc=something,dc=it";
$r = ldap_add($ds, $_dn, $ldaprecord);
}else {
echo "LDAP bind failed";
}
I think it is a little bit more difficult than only replace the mysql functions because of the mysql (or other SQL server) is not similar to LDAP.
I suggest to use an existing PHP package for LDAP. For example Adldap2 looks good for me. And there is many code snippets. For example the authentication
I know this site doesn't like "spot my mistake" code, but I'm desperate. I have a website that needs to access user-specific data from a database (PHP), convert the data into a JSON file, and then change a HTML header to display that specific data. The database table has the user email, password, and class name, among other things. I have a login page that establishes the session variables for the email and the password. When the user logs in, I want their class name to be entered into HTML text. I've used dozens of sources, mostly W3schools, and came up with this code:
PHP:
<?php
session_start();
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
if (!$obj) {
die(mysqli_error());
}
$servername = "localhost";
$username = "id5143969_enviroquest1";
$password = "codeteam1";
$database = "id5143969_enviroquest1";
$link = mysqli_connect($servername, $username, $password, $database);
$result = $link->query("SELECT UserClassName FROM ".$obj->UserInfo1." WHERE ".$obj->UserEmail."= '". mysqli_real_escape_string($link,
$_SESSION['useremail']) . "' and ".$obj->UserPassword." = '" . mysqli_real_escape_string($link, $_SESSION['userpassword']) . "'");
if (!$result) {
die(mysqli_error());
}
$_SESSION['classname'] = $result->fetch_assoc();
if (!$_SESSION['classname']) {
die(mysqli_error());
}
echo json_encode($_SESSION['classname']);
Javascript:
function getclassname() {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "UserInfo1":"UserClassName"};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("UserClassName").innerHTML = myObj;
}
};
xmlhttp.open("GET", "php2.php" + dbParam, true);
xmlhttp.send();
}
HTML:
<h1 class="text-center" id="UserClassName" name="UserClassName" onload=
"getclassname()"> </h1>
I have no idea what's going wrong, and am too new to coding to figure it out by myself.
Try this (I can't test it, but)—
PHP:
Remove the ?> at the end of the file. Pure-PHP files should always leave off the closing tag.
Change (MYSQLI_ASSOC) to just () - per this and the docs, you don't need it.
Javascript:
Remove the session_start() call
Change
for (x in myObj) {
txt += myObj[x].name + "<br>";
}
to
txt = myObj.UserClassName
The fetch_assoc() call in PHP gives you a mapping that uses the database field names ("each key in the array represents the name of one of the result set's columns" per the docs) for a single row. Therefore, if the JSON encode/decode worked OK, you should be able to refer directly to the field.
To test this, in the developer tools, set a breakpoint at the txt = ... line and see what myObj is.
I don't think you need $obj, dbParam, or ?x=, but I would not suggest changing them unless the above doesn't help.
Good luck!
I have an issue that may or may not have been solved before, but I seem to be the only one on here using pure JavaScript instead of JQuery to accomplish my simple AJAX requests.
First here is my AJAX:
function getZestimate(address,csz){
var xmlhttp = new XMLHttpRequest();
var userdata = "address="+address+"&csz="+csz;
xmlhttp.open("POST","../wp-content/themes/realhomes/submit_address.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
retrieve = JSON.parse(xmlhttp.responseText);
document.getElementById("zestimateArea").innerHTML =
'<div id="zillowWrap">
<div id="logoANDtag">
<img src="http://www.zillow.com/widgets/GetVersionedResource.htm?path=/static/logos/Zillowlogo_150x40.gif" width="150" height="40" alt="Zillow Real Estate Search" id="ZillowLogo" />
<span id="zestimateTag">Zestimate®</span>
</div>
<span id="zestimatePrice">'+retrieve[0]+'</span>
</div>
<div id="zillowDisclaimer">
<span>© Zillow, Inc., 2006-2014. Use is subject to Terms of Use</span
<span>What’s a Zestimate?
</div>';
}
else{
document.getElementById("zestimateArea").innerHTML = "Error!"
}
}
xmlhttp.send(userdata);
document.getElementById("zestimateArea").innerHTML = "Generating...";
return false;
}
Next, here is my PHP:
<?php
$zillow_id = '1234';
$search = $_POST['address'];
$citystate = $_POST['csz'];
$address = urlencode($search);
$citystatezip = urlencode($citystate);
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=".$zillow_id."&address=".$address."&citystatezip=".$citystatezip;
$result = file_get_contents($url);
$data = simplexml_load_string($result);
$zpidNum = $data->response->results->result[0]->zpid;
$zurl = "http://www.zillow.com/webservice/GetZestimate.htm?zws-id=".$zillow_id."&zpid=".$zpidNum;
$zresult = file_get_contents($zurl);
$zdata = simplexml_load_string($zresult);
$zestimate=$zdata->response->zestimate->amount;
$street=$zdata->response->address->street;
$city=$zdata->response->address->city;
$state=$zdata->response->address->state;
$zip=$zdata->response->address->zip;
$one='one';
$two='two';
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode(array($zestimate,$street));
?>
What returns in my AJAX is [object Object] with no errors in my Console.
However, see the 2 variables $one and $two? If I place them in the json_encode like echo json_encode(array($one,$two)); it returns one like it is supposed to.
I am not sure what the difference is with the Zillow data. I can echo it individually no problem. But I need to send multiple values to work with. Any ideas?
When you parse a document using SimpleXML, all the nodes are objects which get cast to strings when you try to echo them, but when given to a function like json_encode, you don't get the results you'd expect.
To make them strings so json_encode works, try this:
$zestimate = (string)$zdata->response->zestimate->amount;
$street = (string)$zdata->response->address->street;
echo json_encode([$zestimate, $street]);
I am currently trying to query a database using Ajax. My Ajax Is as follows
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Not working");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.returnhere.value = ajaxRequest.responseText;
}
}
var datepicker = document.getElementById('datepicker').value;
var datepicker1 = document.getElementById('datepicker1').value;
var queryString = "?datepicker=" + datepicker + "&datepicker1=" + datepicker1;
ajaxRequest.open("GET", "detengde.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
From: <input id='datepicker' /> <br />
To: <input id='datepicker1' />
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id=returnhere></div>
My PHP looks like this:
include 'config.php'
$startd = ($_GET['datepicker']);
$endd = ($_GET['datepicker1']);
$sql = "SELECT * FROM delays WHERE Delaytype >= date('".$startd."') AND Delaydate < ADDATE(date('".$endd."'), INTERVAL 1 DAY)";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
do something . .. .. . .
This query works with PHP on its one and will return records that lie between two date ranges.
Im struggling to get the php output back to my page. To be honest when I click the button very little happens. I am confortable with PHP database interactions AJAX is something I just starting to learn.
Please no messages about the security I am aware this is very unsafe.
There is something very fundamental I am missing here. After many tutorials, searching through stacked overflow its just not clicking (no pun intended)
Add a field with a name "returnhere" to the HTML page.
<input type="text" name="returnhere">
If I'm reading your code right, the callback for the ajax function should fill in its value.
<?php
include 'config.php';
header('Content-Type: application/json; charset="utf-8"');
$startd = ($_GET['datepicker']);
$endd = ($_GET['datepicker1']);
$sql = "SELECT * FROM delays WHERE Delaytype >= date('".$startd."') AND Delaydate < ADDATE(date('".$endd."'), INTERVAL 1 DAY)";
$result = mysqli_query($con,$sql);
//just an empty array here
$final_array=array();
while($row = mysqli_fetch_array($result)) {
// I am not aware of what is being returned. So I am going to assume its a 'value'
// you can just store the values returned, in an array and echo the array or
// json_encode($array) and echo that
// this will just echo the value for time the loop encounters this statement
echo $row['value'];
//push the element into the array.Beware of overhead caused by array_push()
//if it is a `key-value` pair, its better just to use $final_array[$key] = $value;
array_push($final_array,$row['value']);
}
// Don't forget to set the header before echoing the json
echo json_encode($final_array);
?>
I hope this helps to some extent. Or if you need particulars feel free to comment below
In your JS
use
document.getElementById("returnhere").value=object.responseText;
or
document.getElementById("returnhere").innerHTML=object.responseText;
which ever suits your need
I am trying to do a basic AJAX implementation to send some form data to a php script and db. I'm just doing this for learning purposes, and have taken it as far as I could. When I hit the "Create Profile" button, nothing is happening. From my code below, does anything obvious jump out at anyone in my syntax/structure?
Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working.
EDIT*** I made some slight changes to the sendFunction(), and have seen some success. Values are now being added to my database, but they values are blank, instead of the values in the form data.
Thank you for all help/suggestions ahead of time!
HTML doc:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax Form</title>
<script language="javascript" type="text/javascript">
function sendFunction() { // Create a function to handle the Ajax
var xmlhttpCreate; // Variable to hold the xmlhttpRequest object
if (window.XMLHttPRequest) { // Checks for browser compatibilities
xmlhttpCreate = new XMLHttpRequest();
}
else {
xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpCreate.onreadystatechange = function() {
if (xmlhttpCreate.readyState == 4) { // If server has processed request and is ready to respond
document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText; // Display a success message that the data was sent and processed by the php script & database
}
}
var fName = document.getElementById('firstName').value; // Dump user firstName into a variable
var lName = document.getElementById('lastName').value; // Dump user lastName into a variable
var queryString = "?fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(); // Send the request
}
</script>
</head>
<body>
<h3>Create Profile</h3><br>
<form name="form">
First Name: <input type="text" id ="firstName"/><br><br>
Last Name: <input type="text" id="lastName"/><br><br>
<input type="button" onclick="sendFunction()" value="Create Profile">
</form><br>
<div id="createSuccess"></div><br>
<h3>Search for Profile</h3><br>
<form name="searchForm">
First Name: <input type="text" id="searchFirstName"/><br><br>
<input type="button" onclick="sendFunction()" value="Search for Profile"/>
</form><br><br>
<div id="resultFN"></div><br>
<div id="resultLN"></div><br>
</body>
</html>
And here is my PHP script:
<?php
// Connect to the database
$con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');
// GET variables from xmlhttpCreate
$fName = $_POST['fName'];
$lName = $_POST['lName'];
// Escape the user input to help prevent SQL injection
$fName = mysqli_real_escape_string($fName);
$lName = mysqli_real_escape_string($lName);
// Build the query
$query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
mysqli_query($con, $query);
mysqli_close($con);
$success = "Profile added to the database";
echo $success;
?>
you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . you can change the javascript code to send with GET like this :
var queryString = "fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);
or you can change the way you get the data on your php file like this:
$fName = $_GET['fName'];
$lName = $_GET['lName'];
don't do both things , only one, change either javascript function or php file.