I have an ajax posting of a form so that I can return values from PHP exactly as it shows here: https://jonsuh.com/blog/jquery-ajax-call-to-php-script-with-json-return/ .
There's a slight difference though, my response.php script is like this:
<?php
session_start();
$email = $_SESSION['email'];
?>
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) {
$action = $_POST["action"];
switch($action) {
case "test": test_function(); break;
}
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
$x = $return["Profile"];
define('DB_NAME', 'STUDENTS');
define('DB_USER', 'STUDENTS');
define('DB_PASSWORD', 'PASSWORD');
define('DB_HOST','HOST');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
$db_selected = mysql_select_db(DB_NAME, $link);
$sql = "UPDATE `STUDENTS`.`Students` SET `Fbprofile` = '$x' WHERE `Students`.`StudEmail` = '$email' ";
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
As you can see, the only difference is that I'm updating an SQL database. The problem is that I want to update the Fbprofile column where StudEmail equals the email session variable. This session variable works perfectly in all other pages, but I can't seem to retrieve it in my response.php. What actually happens is that the SQL update works but only updates all rows that have no email value in them, so I'm guessing it's not reading the $email variable.
Thank you very much for your help.
It's a variable scope problem. You set $email outside of test_function, so it's not visible inside the function. If you had error reporting enabled, you would have seen a notice about the undefined variable.
You should pass it as an argument to the function:
case "test": test_function($email); break;
...
function test_function($email) {
...
}
Related
Objective: I am in the process of creating a php login script.
Problem: I can't seem to be able to make my includes recognize the $connection variable even though it should be clearly defined in connection.php. As a result the value of my variable is nothing / NULL.
What I tried: I started with mysql but quickly noticed that it was the wrong approach and converted my code to mysqli. I checked for typos in all the $connection variables I have. I made sure the paths are correct. As a last resort I did a Google search but didn't find an answer or any useful hint to my scenario.
Problem: What is the reason for my variable not being defined?
Error Messages:
All those messages are related to this single variable no being defined for some reason:
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Common.php on line 4
Php Notice: Undefined variable: connection in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 4
Php Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\aspie\Php\Core\Functions\Members.php on line 5
// INITIALIZER
<?php
session_start();
// error_reporting(NULL);
include 'Connection.php';
include 'Common.php';
include 'Functions/Members.php';
?>
**// ERROR MESSAGES **
<?php
$connection_error = 'Our website is experiencing technical issues, please come back later.';
$wrong_login = 'Password and name are wrong.';
$member_registered = 'Access has been denied. You do not seem to be a registered user.';
?>
**// CONNECTION **
<?php
include 'Errors.php';
$connection = mysqli_connect('localhost', 'root', '', 'project') or exit ($connection_error);
?>
**// COMMON **
<?php
error_reporting();
function sanitize($connection, $data) {
global $connection;
global $data;
return mysqli_real_escape_string($connection, $data);
}
?>
**// MEMBERS **
<?php
function member_registered($connection, $name) {
$name = sanitize($connection, $name);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
?>
**// LOGIN **
<?php
include 'Php/Core/Initializer.php';
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($connection, $name) == false) {
echo $member_registered;
}
}
?>
UPDATE:
Now what I get: existseee;
The conditional doesnt work now even though its all set up right. Username doesnt exist so it should'nt echo "exists:
if (member_registered($connection, 'ee')) {
echo "exists";
}
die("eee");
In your case, the $connection variable inside your sanitize function isn't reachable.
Try to pass the $connection variable into your function, like this:
function sanitize($data, $connection) {
return mysqli_real_escape_string($connection, $data);
}
Read more about it here: http://php.net/manual/en/language.variables.scope.php
UPDATE
In **// MEMBERS ** you need to include the new parameter as well:
function member_registered($name, $connection) {
$name = sanitize($name, $connection);
$query = mysqli_query($connection, "SELECT COUNT(`id`) FROM `members` WHERE `name` = '$name'");
return (mysqli_num_rows($query) == 1) ? true : false;
}
and because of that your **// LOGIN ** should be updated as well:
include 'Php/Core/Initializer.php';
if (member_registered('ee', $connection)) {
echo "exists";
}
die("eee");
echo error_reporting();
if (empty($_POST) == false) {
$name = $_POST['name'];
$password = $_POST['name'];
if (empty($name) OR empty($password)) {
echo $wrong_login;
}
else if (member_registered($name, $connection) == false) {
echo $member_registered;
}
}
And make sure that the $connection variable is reachable everywhere where you need it.
UPDATE #2
Answer to your update:
it should be like this:
if (member_registered('ee', $connection)) {
echo "exists";
}
and not like this:
if (member_registered($connection, 'ee')) {
echo "exists";
}
the $connection is the second parameter.
Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.
I used to store all my data in 000webhost, today I decided to move to hostinger. So.. after moving it I replaced the old mysql_connect info by the new one. Alright, after doing that I tested it, everything has ran fine, except some echo functions.
check file (connects to the server and do the login):
<?php
$servidorr = "mysql.XXXX.co.uk";
$bdd = "XXXXXXXX";
$usuarioo = "XXXXX";
$senhaa = "XXXXXXX";
if (!empty($_POST) AND (empty($_POST['usuario']) OR empty($_POST['senha']))) {
header("Location: geton"); exit;
}
mysql_connect($servidorr, $usuarioo, $senhaa) or trigger_error(mysql_error());
mysql_select_db($bdd) or trigger_error(mysql_error());
$usuario = mysql_real_escape_string($_POST['usuario']);
$senha = mysql_real_escape_string($_POST['senha']);
$lang = mysql_real_escape_string($_POST['lang']);
$sql = "SELECT `id`, `nome`, `nivel` FROM `usuarios` WHERE (`usuario` = '". $usuario ."') AND (`senha` = '". sha1($senha) ."') AND (`ativo` = 1) LIMIT 1";
$updatelang = "UPDATE usuarios SET lang='$lang' WHERE usuario='$usuario'";
$query = mysql_query($sql);
if (mysql_num_rows($query) != 1) {
echo "<script>alert('Oops! Looks like there is something wrong with your login! *perhaps a typo or you did not fill out the fields*'); location.href='geton'</script>"; exit;
} else {
$resultado = mysql_fetch_assoc($query);
mysql_query($updatelang);
if (!isset($_SESSION)) session_start();
$_SESSION['UsuarioID'] = $resultado['id'];
$_SESSION['UsuarioNome'] = $resultado['nome'];
$_SESSION['usuario'] = $resultado['usuario'];
$_SESSION['UsuarioNivel'] = $resultado['nivel'];
$_SESSION['lang'] = $resultado['lang'];
header("Location: http://mapmaking.zz.mu/pages/home"); exit;
}
?>
Home file (these echos are just for testing and this is not the original file, the original one has the same php stuff, except the echo functions, those are in random lines):
<?php
if (!isset($_SESSION)) session_start();
$tlang = $_SESSION['UsuarioLang'];
$aclevel = $_SESSION['UsuarioNivel'];
$nick = $_SESSION['UsuarioNome'];
$neededal = 1;
if (!isset($_SESSION['UsuarioID']) OR ($_SESSION['UsuarioNivel'] < $neededal)) {
session_destroy();
header("Location: http://inside.mapmaking.uk.to/geton"); exit;
}
session_start();
echo $tlang;
echo $aclevel;
echo $nick;
echo "$level$tlang$tlang";
?>
[this one basically start the session and check if the connected user acess level is 1]
Echo $tlang does not work! :( somehow it doesn’t, I have no idea why ;_;
Hope you guys help me, thank you!!
$_SESSION['lang'] != $_SESSION['UsuarioLang']
You assign a value to the first one, yet expect value from the second one.
$_SESSION['lang'] = $resultado['lang'];
$tlang = $_SESSION['UsuarioLang'];
Change this line:
$_SESSION['lang'] = $resultado['lang'];
to the following:
$_SESSION['UsuarioLang'] = $resultado['lang'];
You should also call session_start() without the isset check. Also, you should consider using && instead of AND and || instead of OR, as PHP has weird operator precedence rules (the assignment = has a higher precendence than either AND or OR).
This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 7 years ago.
I'm having some problems performing a mysql query inside a php function. The error I am getting is
Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16
There are several files calling each other so I will attempt to outline the necessary information.
URL Accessed:
localhost/serverList/api/rest.php?action=allServers
serverList/api/rest.php
<?php
include 'inc/restFunctions.php';
$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
$action = $_GET['action'];
}
else{
$action = 'false';
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers();
break;
case 'allEnvs':
$return = allEnvs();
break;
case 'allTypes':
$return = allTypes();
break;
case 'false':
$return = falseReturn();
break;
}
}
serverList/api/inc/restFunctions.php
<?php
include ('inc/config.php');
function allServers(){
$serverInfoQuery = "SELECT * FROM servers"
$allServerResults = $link->query($serverInfoQuery);
$json = array();
while($row = $allServerResults->fetch_assoc()){
$json[]['serverID'] = $row['serverID'];
$json[]['environment'] = $row['environment'];
$json[]['type'] = $row['type'];
$json[]['serverIP'] = $row['serverIP'];
$json[]['serverDescription'] = $row['serverDescription'];
$json[]['serverCreatedBy'] = $row['serverCreatedBy'];
$json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
$json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
$json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
}
$jsonResults = json_encode($json);
return $jsonResults;
}
?>
serverList/api/inc/config.php
<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>
I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.
I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.
The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:
global $link;
See more here:
http://php.net/manual/en/language.variables.scope.php
In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging.
Just pass it as a function parameter - much cleaner and easier to read:
function AllServers($link) {
$serverInfoQuery = "SELECT * FROM servers";
$allServerResults = $link->query($serverInfoQuery);
//More PHP code
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers($link);
break;
}
}
To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:
class DB {
private static $link = null;
public static function getConnectionResource() {
//In that way we "cache" our $link variable so that creating new connection
//for each function call won't be necessary
if (self::$link === null) {
//Define your connection parameter here
self::$link = new mysqli($host, $user, $password, $database);
}
return self::$link;
}
}
function getAllServers() {
$link = DB::getConnectionResource();
//Preform your query and return results
}
Use global variable
function allServers(){
global $link
...
...
...
... your code follows
The following code is part of my ajax notification system and for some reason, it is working only 50%. When I call the code, it runs and then echo's either success or remove but it doesn't seem to change the database values. Any reason? I have tried putting my column names in quotes but that echo's an error. Please help, thanks!
<?php
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
if ($action == 'add') {
$insert = mysql_query("UPDATE updates SET object_fav = '1' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'success';
} elseif($action == 'sub') {
$remove = mysql_query("UPDATE updates SET object_fav = '0' WHERE username = '$username' AND id = '$notid'") or die('Could not connect: ' . mysql_error());
echo 'remove';
} else {
echo 'error';
}
?>
I know it is not the javascript, I have checked the network tab and it is sending the correct values.
If this is the start of the script, you have not called session_start(), and therefore $_SESSION['uname'] will contain an empty value. The query succeeds because it is syntactically correct, but doesn't match any rows and therefore performs no update.
session_start();
require_once('.conf.php');
$notid = mysql_real_escape_string($_GET['notification_id']);
$username = mysql_real_escape_string($_SESSION['uname']);
$action = mysql_real_escape_string($_GET['action']);
Echo $insert and $remove and find which values are missing.