Recently I am learning single page application, but I got a problem, the project I am working on is inside a folder that contain many folders, php js are folders in side the main folder, and each contain its type of files, the problem is that one of the php file called getmax.php gives me the maximum id ,I want to use this max(id) in a js file called module.js in order to give the new module the next id , the module.js should gives this id to another php file called insert.php ,the connection between the module.js and insert.php is working properly if I set the id manually . but I could not figure out how can I make it use the max(id) from the getmax.php file.
note: I noticed lately I'm using MySQL and I should used mysqli I will fix it later.
the getmax.php is:
<?php
// alle relevanten Tabellen abfragen und als json zurückgeben.
$json["status"] = "running";
$details[] = "started get_tables ";
// Include confi.php
include_once('confi.php');
//var_dump($_POST);
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];
$username = $user["username"];
$password = $user["password"];
if($password and $username){
$mySQLstring = "SELECT username, password, id, create_user FROM tbl_user where username = '$username' ;";
$json["statement"][] = $mySQLstring;
$qur = mysql_query($mySQLstring);
//var_dump ( $qur );
if ($qur){
$max = mysql_fetch_assoc($qur);
}
if ($max){
$json["max"] = $max;
if ($max["password"] == $password){
$json["username"] = $username;
$json["id"] = $max["id"];
$json["create_user"] = $max["create_user"];
$json["status"] = "ok";
$tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
//$tables = array("class");
foreach($tables as $table){
if ( $table == 'module' ){
$statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;
//$statement .= ' GROUP BY create_user' ;
$statement .= ' WHERE create_user = 19 ' ;
$qur = mysql_query($statement);
if ($qur){
while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
//var_dump($r);
//echo (json_encode($r));
$result[$table][] = $r;
}
}
}
}
$json = array("status" => "ok", "data" => $result);
}
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
PHP and JS are run on the server and client respectively, and as such you cannot call methods/functions of one from the other. AJAX exists to pass values between JS and serverside code.
Related
I have an HTML/PHP form that uses JAVA SCRIPT function to send (POST) an input content to a PHP code which performs a query and gets back to the JAVA SCRIPT function with data to Auto fill additional inputs in the form.
It all works great when the input content i send is plain text, even if there is a single quote in the content it works.
BUT, as soon as double quotes are included in the input content it fails to return the Auto fill results.
Appreciate your help with indicating where do i fail with passing the quotes.
Thanks
Just to make it clearer, the code works if customer name is "Intel" or "Int'el" , but it fails when customer name is "Int"el"
Here is the JAVA SCRIPT function that sends and receive the data from the PHP:
!--Script Auto fill ltd by customer -->
<script type="text/javascript">
function updatefrm() {
setTimeout(function(){
var customer = $('#customer').val();
if ($.trim(customer) !='') {
$.post('customerfill.php', {customer: customer}, function(data) {
$('#customerupdate').val(data['customer']);
$('#ltdupdate').val(data['ltd']);
});
}
}, 10);
}
</script>
Here is the PHP code that gets the POST data , performs the query, and sends back the array for the JAVA SCRIPT auto fill:
<?php
if (!empty($_POST['customer'])) {
$DB_Server = "localhost"; // MySQL Server
$DB_Username = "XXXX"; // MySQL Username
$DB_Password = "XXXX"; // MySQL Password
$DB_DBName = "XXXXXXXX"; // MySQL Database Name
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Failed to connect to MySQL:<br />" . mysql_error() . "<br />" . mysql_errno());
// Select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Failed to select database:<br />" . mysql_error(). "<br />" . mysql_errno());
mysql_query('SET NAMES utf8');
mysql_query('SET CHARACTER SET utf8');
$safe_name = mysql_real_escape_string(trim($_POST['customer']));
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
if (mysql_num_rows($query) > 0) {
$row = mysql_fetch_assoc($query);
json($row);
} else {
json(null);
}
}
function json ($array) {
header("Content-Type: application/json");
echo json_encode($array);
}
i think your js code is fine and i think error in your php code and in that line
$query = mysql_query(" SELECT * FROM customers WHERE customer = '". $safe_name ."' LIMIT 1 ");
so you should use PDO Prepared Statements for security and not face problem with double quote
$dsn = "mysql:host=localhost;dbname=your_database;charset=utf8mb4";
try {
$pdo = new PDO($dsn, "database_username", "database_password");
} catch (Exception $e) {
echo "no connection";
exit();
}
$stmt = $pdo->prepare("SELECT * FROM customers WHERE customer = :customer LIMIT 1");
$stmt->execute(array(":customer"=>$safe_name));
$row = $stmt->fetch();
I'm working on a script that forms a web page based on what is in my database. For his I call a java script function when the page loads and whenever the page needs to update.
Firstly I made a script that gets the information from the database, passes it to java script by echo "var region_list = ". $js_region_list . ";\n"; and then proceeded to generate the page itself which worked.
After that I tried to get this to work based on an AJAX request but this failed horribly. As it stands I get correct information from the database but it does not change the value of echo "var region_list = ". $js_region_list . ";\n"; which prevents the page from updating.
The PHP part of my script:
if(isset($_POST["campaign_id"])){
// Get variables and sanetize
$campaign_id = preg_replace('#[^0-9]#i', '', $campaign_id);
// Create planet list
$planet_list = array();
$sql = "SELECT planet_nr, size, moon FROM planets WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($planet_list, array($row["planet_nr"],$row["size"],$row["moon"]));
}
/* free result set */
mysqli_free_result($result);
}
// Create region list
$region_list = array();
$sql = "SELECT planet_id, region_id, region_type, owner FROM regions WHERE campaign_id = $campaign_id";
if ($result = mysqli_query($db_conx, $sql)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
array_push($region_list, array($row["planet_id"],$row["region_id"],$row["region_type"],$row["owner"]));
}
/* free result set */
mysqli_free_result($result);
}
// Convert array's for use in java
$js_planet_list = json_encode($planet_list);
$js_region_list = json_encode($region_list);
$list = array($planet_list, $region_list);
$list = json_encode($list);
echo $list;
exit();
The javascript part:
<?php
echo "var planet_list = ". $js_planet_list . ";\n";
echo "var region_list = ". $js_region_list . ";\n";
?>
var ajax = ajaxObj("POST", "campaign.php?c="+campaign_id);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "Fail"){
alert(ajax.responseText);
}
}
}
ajax.send("campaign_id="+campaign_id);
NOTE: These are just snippets of the whole script. The whole script is in the same PHP file with the PHP up above between it's tags and the java down between the script tags.
In your ajax success part, you need to just update the values of the the variables planet_list and region_list as shown below
planet_list = JSON.parse(ajax.responseText[0]);
region_list = JSON.parse(ajax.responseText[1]);
I am attempting to use JavaScript and Jquery to search a database. I have set up a generic query.php file so that I can pass in the database and query and have it return an array. For some reason, when I try to select all using the *, my PHP server crashes with:
I am using the built in server with PHP 7.0.2. I am attempting to retrieve information from a Oracle database.
Here is the post statement:
$.post(DB1.filename,
{sid: DB1.sid,
username: DB1.username,
password: DB1.password,
host: DB1.host,
port: DB1.port,
sql: query},
function(res){
if(res == -1){
res = errorCode(DATABASE_CONNECTION_ERROR);
} else {
var a = parseObject(res);
var t = parseTable(a);
elements[TABLE].element.innerHTML = t;
}
log(FILE_NAME, "RETRIEVED query ");
}
);
Here is the query.php:
<?php
/* This script will connect to a database and search the given SQL string.
If the connection cannot be established, it will return -1. Otherwise, it will return a JSON array.
*/
//Parameters
$sql = $_POST["sql"];
//Database Information
$user = $_POST["username"];
$pass = $_POST["password"];
$host = $_POST["host"];
$port = $_POST["port"];
$sid = $_POST["sid"];
$connection = "(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = " . $host .")(PORT = " . $port . ")) (CONNECT_DATA = (SID = " . $sid . ")))";
//Establish connection
$conn = oci_connect($user, $pass, $connection);
//Check connection
if(!$conn){
echo -1;
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
oci_fetch_all($stRows, $res); //This is where the everything actually crashes
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
So if I set the query as:
query = "select TABLE_NAME from ALL_TABLES";
everything works just fine. A table with a single column will be printed to the screen.
However, if I run:
query = "select * from ALL_TABLES";
I get the error above.
This happens regardless of which table I am attempting to connect to. My credentials are correct and I have tried different credentials as well. Any ideas why this is happening?
--UPDATE--
I tried hard coding the column names. I can select up to 8 columns before it crashes.There are 152 rows.
I circumvented the error by swapping the oci_fetch_all for oci_fetch_array as follows:
<?php
...
} else {
//Query for the given SQL statement
$stRows = oci_parse($conn, $sql);
oci_execute($stRows);
$res = array();
while($row = oci_fetch_array($stRows, OCI_NUM)){
$res[] = $row;
}
echo json_encode($res);
//Close the connection
oci_close($conn);
}
?>
This meant drastic changes to the function used to decode the JSON object array, but it does work. I will not mark this answer as correct though because I would very much like to know why my original code wasn't working...
I am making use of jQuery's Autocomplete where I am populating my autocomplete dropdown with a php file called site.php. Site.php gets the values from a mysql table called site and which has 3 columns: id, code and site. I want my autocomplete to show only code and site and then store the corresponding id in my other table.
Everything works fine except that autocomplete is posting the code and the site selected but not the id. What do I need to change in order to send the id to my php POST and not code and site? Scripts as follows:
PHP file: site.php
<?php
$server = 'sql203.com';
$user = 'xxxxxxxxxxxx';
$password = 'xxxxxxx';
$database = 'b17';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
/* retrieve the search term that autocomplete sends */
$term = trim(strip_tags($_GET['term']));
$a_json = array();
$a_json_row = array();
if ($data = $mysqli->query("SELECT * FROM `b17_16413362_upupa`.`site` WHERE code LIKE '%$term%' OR site LIKE '%$term%' ORDER BY code , site")) {
while($row = mysqli_fetch_array($data)) {
$id = htmlentities(stripslashes($row['id']));
$code = htmlentities(stripslashes($row['code']));
$site = htmlentities(stripslashes($row['site']));
$a_json_row["id"] = $id;
$a_json_row["value"] = $code.' '.$site;
$a_json_row["label"] = $code.' '.$site;
array_push($a_json, $a_json_row);
}
}
// jQuery wants JSON data
echo json_encode($a_json);
flush();
$mysqli->close();
?>
Javascript:
<script type="text/javascript">
$(function() {
$("#sitex").autocomplete({
source: 'site.php',
minLength: 0
}).focus(function(){
$(this).autocomplete("search");
});
});
</script>
In your PHP, change
$a_json_row["value"] = $code.' '.$site;
to
$a_json_row["value"] = $id;
The 'value' property is the data that will be submitted by the form. The 'label' property is what will be displayed to the user.
I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).