I am using a HTTP query string to pass an id. The variable I assign it to works perfectly for the queries immediately following. However, it doesn't work within any of the functions which I define in the same file, although I declared the variable as global.
$circleID = $_GET['id'];
$circleID works well for this query:
// Retrieve circle data
$circleDataResult = mysqli_query($connection," SELECT name, description
FROM circle
WHERE circleID = '$circleID' ");
$circleData = mysqli_fetch_array($circleDataResult);
$circleName = $circleData['name'];
$circleDesc = $circleData['description'];
It doesn't work within the following function though. $circleID seems to be empty in this context:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'removeUser' : removeUser(); break;
case 'makeAdmin' : makeAdmin(); break;
case 'revokeAdmin' : revokeAdmin(); break;
case 'makeOwner' : makeOwner(); break;
}
}
function removeUser(){
global $connection;
global $circleID;
$thisUserID = $_POST['id'];
$removeUserFromCircle = " DELETE
FROM circle_participants
WHERE circleID = '$circleID' AND userID = '$thisUserID' ";
if (mysqli_query($connection, $removeUserFromCircle)) {
echo "You removed " . getName($thisUserID) . " from this circle";
} else {
echo "Error deleting record: " . mysqli_error($connection);
}
}
Apologies if this is a trivial question. I am new to php and spent a considerable amount of time trying to solve this, but I'm stuck.
In order to sum up the answer for anyone else encountering the problem:
It seems like the id value I wanted to retrieve via GET from the HTTP query string value was overwritten/set to null by the POST request, as user3411846 pointed out. Thus, when the code was executed via AJAX, circleID was set to null.
Using session variables in conjunction with if(isset){} solved the problem!
This is the bit of code I changed:
if(isset($_GET['id'])){
$_SESSION['circleid'] = $_GET['id'];
}
instead of:
$circleID = $_GET['id'];
And within the function:
function removeUser(){
...
$circleID = $_SESSION['circleid'];
...
}
instead of:
function removeUser(){
...
global $circleID;
...
}
See why this will not work
Suppose that you have sent an get request to a page
$a = $_GET['variable'];
echo $a ; // this will echo the variable
exit;
Now you are making once again the post request to this page
$a=$_POST['variable'];
echo $a; // will print data if there exist data in the given variable
exit;
Now since you want to access the previous get data in the post data you have to save the get data in the session since on the next request all the data from the previous request will be lost
so in starting of the page
session_start()
$circleid = $_GET['id'];
$_SESSION['cirlceid'] = $circleid;
and in the remove function
function removeUser(){
global $connection;
$circleID = $_SESSION['circleid']
$thisUserID = $_POST['id'];
$removeUserFromCircle = " DELETE
FROM circle_participants
WHERE circleID = '$circleID' AND userID = '$thisUserID' ";
if (mysqli_query($connection, $removeUserFromCircle)) {
echo "You removed " . getName($thisUserID) . " from this circle";
} else {
echo "Error deleting record: " . mysqli_error($connection);
}
}
Related
I have a PHP script that is split into two separate PHP scripts (As they each serve a purpose and are quite lengthy). For simplicity let's call these 1.php and 2.php.
Script 1.php does an API call to a website passes the payload to a function. Once has truncated and inserted the new records into the table, it then includes the 2nd script. This is where the issue begins. Seemingly when I query the marketPlace table it returns a null array however if I insert a sleep(1) before I include 2.php it works! I can only summize that somehow the truncate and insert queries in 1.php had not completed before the next queries were called? (I've never come across this before!).
There is only one database connection and is defined by a database class which is contained in 1.php:
class Database
{
// This class allows us to access the database from any function with ease
// Just call it with Database::$conn
/** TRUE if static variables have been initialized. FALSE otherwise
*/
private static $init = FALSE;
/** The mysqli connection object
*/
public static $conn;
/** initializes the static class variables. Only runs initialization once.
* does not return anything.
*/
public static function initialize()
{
Global $servername;
Global $username;
Global $password;
Global $dbname;
try {
if (self::$init===TRUE)return;
self::$init = TRUE;
self::$conn = new mysqli($servername, $username, $password, $dbname);
}
catch (exception $e) {
date('Y-m-d H:i:s',time()) . " Cant' connect to MySQL Database - re-trying" . PHP_EOL;
}
}
public static function checkDB()
{
if (!mysqli_ping(self::$conn)) {
self::$init = FALSE;
self::initialize();
}
}
}
The function that trunctated and inserted into the marketplace is:
function processMarketplace($marketData) {
// Decode to JSON
$outputj = json_decode($marketData, true);
$marketplaceCounter = 0;
// Check for success
if (($outputj['success']==true) && (!stristr($marketData, "error"))) {
// Create the blank multiple sql statement
$sql = "TRUNCATE marketplace;"; // Clears down the current marketPlace table ready for new INSERTS
//Loop through each multicall
foreach ($outputj['multiCall'] as $orderBook) {
foreach ($orderBook['marketplace'] as $orderLine) {
$type = $orderLine['type'];
$price = $orderLine['amountCurrency'];
// Add new SQL record (This ignores any duplicate values)
$sql .="INSERT IGNORE INTO marketplace (type, price) VALUES ('" . $type . "'," . $price . ");";
}
$marketplaceCounter++;
}
// Now run all the SQL's to update database table
if (strlen($sql) > 0) {
if (Database::$conn->multi_query($sql) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql . "<br>" . Database::$conn->error;
}
}
echo date('Y-m-d H:i:s',time()) . " == Marketplace Orderbook retreived == <BR><BR>" . PHP_EOL;
} else {
echo date('Y-m-d H:i:s',time()) . " Failed to get Marketplace data. Output was: " . $marketData . "<BR>" . PHP_EOL;
die();
}
}
I've chased this around for hours and hours and I really don't understand why adding the sleep(1) delay after I have called the processMarketplace() function helps. I've also tried merging 1.php and 2.php together as one script and this yields the same results. 2.php simply does a SELECT * FROM marketPlace query and this returns NULL unless i have the sleep(1).
Am I missing something easy or am I approaching this really badly?
I should add I'm using InnoDB tables.
This is how its called in 1.php:
$marketData = getData($user,$api); // Get Marketplace Data
processMarketplace($marketData); // Process marketplace data
sleep(1); // Bizzare sleep needed for the select statement that follows in 2.php to return non-null
include "2.php"; // Include 2nd script to do some select statements on marketPlace table
2.php contains the following call:
$typeArray = array('1','2','3');
foreach ($typeArray as $type) {
initialPopulate($type);
}
function initialPopulate($type) {
// Reset supplementary prices
mysqli_query(Database::$conn, "UPDATE marketPlace SET price_curr = '999999' WHERE type='" . $type . "'");
echo mysqli_error(Database::$conn);
// Get marketplace data <--- This is the one that is strangely returning Null (after the first loop) unless I place the sleep(1) before including 1.php
$query = "SELECT * FROM marketPlace WHERE type='" . $type . "'";
$result = mysqli_query(Database::$conn, $query);echo mysqli_error(Database::$conn);
$resultNumRows = mysqli_num_rows($result);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
// Get information from the offertypes table
$query2 = "SELECT offerID FROM queryTypes WHERE type='" . $type . "'";
$result2 = mysqli_query(Database::$conn, $query2);echo mysqli_error(Database::$conn);
// Create array from mysql data
$rows2 = array();
while($r2 = mysqli_fetch_row($result2)) {
$rows2[] = $r2;
}
// Loop through marketplace data and apply data from the offertypes table
$sql1 = ""; // Create a blank SQL array that we will use to update the database
$i = 0;
foreach ($rows as $row) {
$sql1 .= "UPDATE marketPlace SET enrichmentType = " . $rows2[$i][0] . " WHERE type='" . $type . "';";
$i++;
}
// Now run all the SQL's to update database table
if (strlen($sql1) > 0) {
if (Database::$conn->multi_query($sql1) === TRUE) {
echo mysqli_error(Database::$conn);
//echo "New records created successfully";
} else {
echo mysqli_error(Database::$conn);
echo "Error: " . $sql1 . "<br>" . Database::$conn->error;
}
}
}
You are using mysqli:multi_query.
Unlike query, multi_query does not retrieve the results immediately. Retrieving the results must be done using mysqli::use_result
An example from the documentation:
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
You don't need to print the results, but if you don't retrieve them, you are not guaranteed the INSERT has completed.
Note in the documentation for use_result at
https://www.php.net/manual/en/mysqli.use-result.php
it states
"Either this or the mysqli_store_result() function must be called
before the results of a query can be retrieved, and one or the other
must be called to prevent the next query on that database connection
from failing."
As a result of not calling store_result or use_result, you are having unpredictable results.
what my code does now is its posting the session in the database and everytime I refresh this page it keeps posting the same session again and again. I don't get why? The solution is probably a simple one but I tried everything. Hope to get some help.
<?php
session_start();
require '../../required/connection.php';
require '../../required/functions.php';
if (!isset($_SESSION['alive']))
{
$id = $_GET['trxid'];
$_SESSION['alive'] = uniqid();
$currentSession = $_SESSION['alive'];
$checkQuery = "SELECT token FROM request_data WHERE token='$currentSession'";
$checkResult = mysqli_query($con, $checkQuery);
$row = mysqli_num_rows($checkResult);
if($row < 1)
{
$firstQuery = "INSERT INTO request_data (token, link) VALUES ('$currentSession', '$id')";
$firstResult = mysqli_query($con, $firstQuery);
}
}
I think that something went wrong in your connection.php or functions.php. Is it also possible that you have server errors that lead to this behavior? Further it could be that you have modified the configurations of sessions in the php.ini (for example the lifetime)?
The following example is based on your code and works on the page phpfiddle.org
<?php
session_start();
// just for testing - you can comment it in and out
//$_SESSION['alive'] = null;
if (!isset($_SESSION['alive'])) {
echo 'FALSE; <br/>';
$_SESSION['alive'] = uniqid();
echo 'AFTER = "'. $_SESSION['alive'] . '"';
} else {
echo 'TRUE = "'. $_SESSION['alive'] . '"';
}
?>
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
Solution found, but new problem occured - displayed at bottom of this question
I have created this while loop which shows all content from my db and gives the user the possibility to edit it by entering a new value and pressing the 'Update' button. Everything works fine except that when I press the 'Update' button, the value of my object is erased in stead of updated. So the value of my input field becomes blank, but it has to display the value that was filled in.
I'm almost certain that the problem is within the last part my PDO code (in the function Update), but can't point my finger on it. Can you help me?
Connection to my PDO code
<?php
include_once('classes/Day.class.php');
$d = new Day();
$all = $d->getAll();
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
}
?>
My while loop
<?php
while ($displayAll = $all->fetch(PDO::FETCH_ASSOC)) {
echo
"
<form method='POST' action=''>
<label>Day " . $displayAll['id'] . ":</label>
<input type='text' name='myreport' value='" . $displayAll['myreport'] . "' />
<input type='hidden' name='hidden' value='" . $displayAll['id'] . "' />
<button type='submit' name='update''>Update</button>
</form>
";
}
?>
My functions
<?php
include_once('Db.class.php'); // connection to the Db.
class Day{
private $m_iId;
private $m_sMyreport;
public function __set($p_sProperty, $p_vValue){
switch($p_sProperty){
case 'Id':
$this->m_iId = $p_vValue;
break;
case 'Myreport':
$this->m_sMyreport = $p_vValue;
break;
}
}
public function __get($p_sProperty){
switch($p_sProperty){
case 'Id':
return $this->m_iId;
break;
case 'Myreport':
return $this->m_sMyreport;
break;
}
}
public function Update(){
$conn = Db::getInstance();
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$statement = $conn->prepare("
UPDATE `tbl_dailyreport`
SET `myreport` = :myreport
WHERE `id` = :id
");
$statement->bindValue(":myreport",$this->m_sMyreport);
$statement->bindValue(":id",$this->m_iId);
$statement->execute();
}
public function getAll () {
$conn = Db::getInstance();
$result = $conn->query("SELECT * FROM tbl_dailyreport");
return $result;
}
}
?>
All help is appreciated!
Edit: solution found + new problem
$d->Report = $_POST['myreport'];
in "Connection to my PDO code" has to become
$d->Myreport = $_POST['myreport'];
because it has to be equal to the case items in the setter and getter. The annoying thing now is that when I press 'Update' the previous message is still visible, so I have to double refresh. Any solutions for this?
If I understand You correctly You will have to load current results just after the update:
if(isset($_POST['update'])){
$d->Report = $_POST['myreport'];
$d->Id = $_POST['hidden'];
$d->Update();
$all = $d->getAll();
}
This way, after the update You will have fresh (updated) results that You can display in My while loop.
I want to use a MySQL Query in a function to retrieve information from a table:
function selectFromMemTable($a) {
$query="SELECT * FROM members WHERE username = '" . $a ."'";
$result = mysql_query($query) or die ("FOUT: " . mysql_error());
while (list($id, $a, $b, $c, $d, $e, $f) = mysql_fetch_row($result)){
$user_id = $id;
$user_usernaam = $a;
$user_voornaam = $b;
$user_achternaam = $c;
$user_email = $d;
$user_password = $e;
$user_admin = $f;
}
}
In the script I want to use the following code to retrieve the $user_id.
selectFromMemTable(username);
echo $user_id;
When loading page I receive the following error:
Fatal error: Call to undefined function selectFromTable() in test.php on line 28
Without the function it works correctly. What is the problem?
Sorry, the correct script is:
selectFromMemTable($_COOKIE["user"]);
echo $user_id;
You named your function selectFromMemTable but are calling selectFromTable. That's the wrong name.
Check the name of your function. The comiler says you try to call a function with a different name.
In your function selectFromMemTable you should return the selected values or global the vars. Because you cannot access them until they are private only.
Never trust incoming request vars! Yo should escape $_COOKIE["user"] for use in databse query (use mysql_real_escape_string or the newer mysqli_real_escape_string).
Since there matches only 1 user per username you should LIMIT the selected rows to 1.
Be aware of using the username directly from cookie to access private userdata. For security reasons you should use a individual session ID or a cryptographic stronger individual qualifier for use with cookies. That's because actually the user can change it's name in the cookie value and than he's logged in as another user.
You can fetch an assoc - it's easyer to access and you don't need to set tons of variables.
Function declaration:
function selectFromMemTable($a)
{
$query = sprintf("SELECT * FROM members WHERE username = '%s' LIMIT 1",
mysql_real_escape_string($a));
$result = mysql_query($query) or die ("FOUT: " . mysql_error());
return mysql_fetch_assoc($result);
}
Use the function:
$user = selectFromMemTable($_COOKIE["user"]);
if(!$user)
echo "no user";
else
echo $user['id'];
Edit: Maybe you have to change the id in $user['id'] to the right column name.