$_GET PHP is misbehaving - javascript

I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.

The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";

Related

Forms not rendering from database

I am using formbuilder plugin (https://formbuilder.online/) in jquery and I am trying to create a php application that stores forms in mysql database for a user. I am not able to display the forms on back from database to the html. Form data is in JSON.
I have tried a lot of different things and I am running out of ideas. Any suggestions would be helpful. I just need the right direction to think.
PHP file (form.php)
$dbhost = 'localhost';
$dbuser = 'abc';
$dbpass = 'password';
$dbname = 'xyz';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "SELECT id, code FROM data";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["code"];
}
} else {
echo "0 results";
}
mysqli_close($link);
Jquery File
$('ul li a').click(function (e) {
$.post("./form.php", function (text) {
toggleEdit();
var renderedForm = $('.render-wrap');
formRenderOpts = {
dataType: 'json',
formData: text
};
console.log(text);
renderedForm.formRender(formRenderOpts);
});
});
So, I am getting all the entries for JSON in console. But I am looking for single entry. For example, lets say I have 2 forms stored in database I want to display 1st form on the website. Instead I am not getting anything displayed. But I am getting all the entries in JSON format in console. I new to PHP and I think that is why I am not able to figure this out.

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

Having Issue on Getting Second Session Variable in JavaScript

I have a PHP file getting data from my SQL database and I am trying to set and get two session variables like $_SESSION['fname'] and $_SESSION['userID'] by $theFName and $theId.
$email = $_POST['email'];
$pass = $_POST['pass'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
$sql = "SELECT id, email, fname, lname, type FROM users WHERE `email`=? AND `pass`=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $email,$pass);
$stmt->execute();
$stmt->bind_result($theId,$theEmail,$theFName,$theLname,$theType);
if ($stmt->fetch()) {
echo 'true';
$_SESSION['LOGIN_STATUS'] = true;
$_SESSION['fname'] = $theFName;
$_SESSION['userID'] = $theId;
} else {
echo 'false';
}
in JavaScript file I have
<script>
var tok = "var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
but I am getting empty string!
can you please let me know what I am doing wrong?
I'm not quite sure I understand what you are trying to do in the JS file, but it is not valid JS in any case - the quotes don't match and it seems like you are trying to do an assignment inside a string.
I think what you are looking for is something more along the lines of this:
<script>
var UID = "<?php echo $_SESSION['userID']; ?>";
console.log("The Id is " + UID)
</script>
However, please note that dynamically generating JS files using PHP is likely not the best way to go about this. Check out this SO answer on the various methods you can use to pass variables from PHP to JS, along with their various pros and cons.

Access DB from html file via custom PHP file

Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>

Does SJCL content need to be json_encode(d) when it is read from a database?

Overview
I am attempting to encrypt data, send it to a database, then decrypt the data using the Stanford Javascript Crypto Library (SJCL).
Problem
Whenever I attempt to call the data from the database, I get a "CORRUPT: ccm: tag doesn't match" error. I have looked this up and it seems as if my content or password is corrupted, and because the password is being straight from a textbox, I have narrowed it down to the content.
Code Snippet
(PHP)
$paste = $_GET['url'];
$query = "SELECT * FROM posts WHERE url='$paste'";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_array($result);
$t = $row['title'];
$c = $row['content'];
$con = json_encode($c);
$e = $row['encode'];
$ca = $row['Catagory'];
$en = $row['encrypted'];
(Javascript) -Invokes SJCL-
<script type="text/javascript">
var content = <?php echo $con; ?>;
function decryptPaste() {
try {
sjcl.decrypt(document.getElementById("decrypt-pass").value, content)
} catch (e) {
alert("Can't decrypt: " + e);
}}
Any and all help appreciated, thanks in advance!

Categories