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!
Related
I'm currently trying to code a dumb website for a class. I'm trying to access my PHP file to check if the name exists inside the database or not. When it does, it needs to return either a 1 or 0 back to the javascript part. Is there a real way to do that?
The reason for the return is in case the name does exist, it will just send an alert to the user that hey the name exists, move along.
Note I'm using the tutorials from w3school.com in case my code looks like some amateur level sh*t.
javascript:
function checking(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "checker.php?firstname=" + firstname + "&lastname=" + lastname, true);
xmlhttp.send();
alert (queue);
}
php:
<?php
session_start();
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
$yes = 1;
$no = 0;
//Information needed in order to access database
$dbname = "**********************";
$servername = "localhost";
$username = "************************";
$password = "************";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql_query = "SELECT firstname, lastname FROM queue_1 WHERE firstname='".$firstname."' and lastname='".$lastname."'";
$result = mysqli_query($conn,$sql_query);
$row = mysqli_num_rows($result);
if($row == 1){
echo ($yes);
}
else
{
echo ($no);
}
?>
I see a few issues here, your JS code is attempting to access an undefined variable (at least in the context of the function you posted) queue.
Outside of your PHP code, make sure that the JS is handling the response coming from PHP, do this by attaching an event listener to your request.
The load event will trigger when your PHP script completes, you can point this to a named function if your code will be more complex than just an alert.
More info here MDN Docs
function checking(){
var xmlhttp = new XMLHttpRequest() ;
xmlhttp.addEventListener("load", function () {
alert(this.responseText);
});
xmlhttp.open("GET", "checker.php?firstname=" + firstname + "&lastname=" + lastname, true);
xmlhttp.send();
}
This is under the assumption that you're trying to display the response text as an alert message.
Additionally, beware passing unfiltered user input into an SQL query, this can lead to injection attacks, I'd suggest you change your PHP code to use prepared statements from the mysqli lib.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql_query = "SELECT firstname, lastname FROM queue_1 WHERE firstname=? AND lastname =?";
$stmt = $conn->prepare($sql_query) ;
$stmt->bind_param('s', $firstname);
$stmt->bind_param('s', $lastname);
$stmt->execute();
$stmt->store_result();
echo $stmt->num_rows === 1 ? $yes : $no;
$stmt->free_result() ;
$stmt->close() ;
More info about mysqli can be found here if some of this is confusing mysqli documentation
And on a final note, on your sql if you are looking for the existence of a record only, it tends to be faster to do SELECT 1 FROM table WHERE fieldname=? LIMIT 1 as you are not using the result set for this.
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've been trying my hardest to understand the lessons in W3Schools but it is not working somehow!
I've edited it so that you guys would get it much better.
This is the index.html page:
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var myObj, i, x, j = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.stringify(this.response);
myObj1 = JSON.parse(myObj);
document.getElementById("demo").innerHTML = myObj1.stuid;
alert(myObj1);
}
};
xmlhttp.open("GET", "sing.php", true);
xmlhttp.send();
</script>
</body>
</html>
And here is the sing.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "sacapp";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT stuid, stuname, stucourse, stustat, stulyear, stulog FROM stuinfo");
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
and here is the result of myObj1 [{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"InfoTech","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"CivilEngi","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]
but the document.getElementById("demo").innerHTML = myObj1.stuid; only returns an Undefined answer... what went wrong here?
I don't know what the hell is wrong with it. Can someone please point out any mistakes?
Remove the html from sing.php and only return JSON. Even though you see the correct output in your browser, if you view the source you'll notice the , etc. tags. Your script is seeing those and failing.
It looks like the AJAX request returns HTML, you can check what's being returned by using an alert, change the code to this:
if (this.readyState == 4 && this.status == 200) {
alert(xmlhttp.responseText);
}
If there is HTML in the alert, you should check if the path of the sing.php page is correct in the line:
xmlhttp.open("GET", "sing.php", true);
UPDATED ANSWER.
Ok, I checked everything and had a local setup. You have many mistakes in your code.
Let's take a look at index.html.
It should look like this. (I added comments where you made mistakes.)
<!DOCTYPE html>
<html>
<body>
<h2>Get data as JSON from a PHP file on the server.</h2>
<p id="demo"></p>
<script>
var myObj, i, x, j = "";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this);
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.response); //**IT'S 'response' NOT 'responseText' To look at the object data, you can do console.log(myObj) and see what the object looks like. in the developer window**
document.getElementById("demo").innerHTML = myObj.student_id; //**YOU DON'T HAVE A PROPERTY 'id' BUT YOU DO HAVE 'student_id', again look at the json object in the developer window. **
}
};
xmlhttp.open("GET", "sing.php", true);
xmlhttp.send();
</script>
</body>
</html>
As for 'sing.php', since I don't have your database, I created my own arrays so that I could merge them since I think this is what you're trying to do.
<?php
$outp = array(
'student_id' => '10-00000',
'student_name' => 'Breaker M. North',
'student_course' => 'BSIT',
'student_stat' => 0,
'student_log' => 1
);
$outp2 = array(
"stu_log" => 2,
"course_name" => "IT 202",
"student_id" => "10-00000"
);
echo json_encode(array_merge($outp, $outp2));
?>
When you do echo json_encode($outp + $outp2); you're actually creating and new array and putting $outp and $outp2 as separate values. That's why you had the [], you had two values and not only one. You then had undefined because you couldn't access the property, instead you we accessing the first element of the json array.
On a side note, you could create only one SQL request by using JOIN on student_id... but this is not part of the question.
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)";
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.