-1

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.

lukman
  • 95
  • 1
  • 7
  • 3
    [Mandatory SQL injection warning](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – jDo Apr 20 '16 at 23:54
  • 3
    *"but '$sql2' doesn't."* - Simple; you never executed it. And if `$lecturer` is a string in `VALUES ($lecturer,'Jane')`, that will fail you also. – Funk Forty Niner Apr 20 '16 at 23:55

1 Answers1

0

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')";
Christian Bonato
  • 1,253
  • 11
  • 26