SQL can read $_POST variable but PHP can't

So i have a php file which receives two variables from another file with jquery ajax with POST method. If i echo these two variables i find out that they are empty.I verify this by using an echo if it is empty BUT if i insert them to my database with an insert query i find out that they have a value . Am i getting crazy? I tried many methods to extract the value from the $_POST but i failed. Note that the jquery ajax which sends the two variables works as intended because my database has the correct values inserted.
if you want the rest of the code or something else please ask me ,work with me because this problem troubles me much

This is where i call it.

           data: { user1:'<?php echo $uid; ?>',  user2:profileId[k] }

This is chat.php

         require_once 'online-users.php';
         include 'dbconnect.php';

         $user1 = !empty( $_POST['user1'] ) ? $_POST['user1'] : false;
         $user2 = !empty( $_POST['user2'] ) ? $_POST['user2'] : false;
          if (empty($user1)) {
           echo "yes";
          $sql    = "SELECT chatLog FROM chat WHERE firstId = '".$user1."' AND secondId = '".$user2."' "; 
          $result = mysqli_query($conn, $sql);
          $count = mysqli_num_rows($result);
        	if($count == "0"){
                    $sql1 = "INSERT INTO chat (firstId, secondId) VALUES ('".$user1."', '".$user2."')";
                    $result1 = mysqli_query($conn, $sql1); 
                    while ($row = mysqli_fetch_assoc($result)) {
                           $log = $row['chatLog'];

         $uid = $session;
         if( !isset($_SESSION['user']) ) {
          header("Location: index.php");


And this is proof that the numbers are being saved in the database and that they have value indeed.

The problem here is a lack of logic.

There are a lot of logically incorrect statements in your question.
For example, there is no $_POST variable to be recognized by whatever “SQL” in thos code. There is only a single ordinary PHP variable $user1 in question.
Not to mention that a variable obviously cannot be empty and non-empty at the same time.

Your ways to proof the behavior are logically incorrect either. You are checking some indirect consequences instead of checking the variable itself - it just makes no sense.

You need to brace yourself and verify everything again, strictly following the formal logic. It always helps.

PS. And I kind of love the SQL injection here. It’s 2017 today, 20th anniversary for PHP, but most PHP codes are still vulnerable to this ridiculous vulnerability

I’m a bit confused by some elements of the PHP code, but then most of it is stuff I haven’t tried, so it may well be me.

First, you start an output buffer using ob_start(), but you never close it. The documentation for that function isn’t really clear about what happens in that event (ETA - nothing apparently, still just sends the output back), but as you’ve called it using Ajax, the output from the script will only be displayed by the success function in the calling code, surely?

For that same reason, I am unclear as to why you try to perform a header redirect towards the end of the code. Isn’t the entire purpose of calling the routine using Ajax to stop having to do this stuff, and will it even have any effect when called that way? And if you want to see whether the user is logged in, perhaps before the database update would be a better time.

What’s the point of the contents of the else clause after you run the first query? You loop through a set of results from the SELECT, assign one of the column values to a variable, then do nothing with it.

What happens if you var_dump($_POST) right at the top of your PHP code, and echo it in your success() function in the calling code? Exactly what is in the array?

1 Like

if i var_dump the $_POST i get NULL . Another strange thing is that if i echo back at the success function i get the correct value. The value of the variables are int numbers .Let me explain.
let’s say that ‘<?php echo $uid; ?>’ is number 1 and profileId[k] is number 10

I made some changes to make it easier for you to understand . I moved all the php code to a seperate file called chatusersquery.php

 include 'dbconnect.php';
 $user1 = $_POST[user1];
 $user2 = $_POST[user2];
 $time = time();
 $time_check = $time-300;
  $sql    = "SELECT chatLog FROM chat WHERE firstId = '".$user1."' AND secondId = '".$user2."' "; 
  $result = mysqli_query($conn, $sql);
  $count = mysqli_num_rows($result);
	if($count == "0"){
            $sql1 = "INSERT INTO chat (firstId, secondId, time) VALUES ('".$user1."', '".$user2."', '".$time."')";
            $result1 = mysqli_query($conn, $sql1); 
  $sql2 = "DELETE FROM chat WHERE time<$time_check"; 
  $result2 = mysqli_query($conn, $sql2);

  echo $user1;


i pass the data to the above php from home.php using jquery ajax : (i entered a 2 second delay at the redirection because i thought that there was a problem with this…anyway)

$.post("chatusersquery.php", { user1:'<?php echo $uid; ?>', user2: profileId[k]}, function(data){ var timer = setTimeout(function() {
                                                                         }, 2000);  });

and lastly i call again the chatusersquery,php to retreive the data back at chat.php which never happens :
tried this :

        url: 'chatusersquery.php',
        dataType: 'text',
        success: function(data)


and this:(of course by first encoding the data at the chatusersquery.php)

$.getJSON("chatusersquery.php", function(data) { 
    alert(data.user1 + data.user2);

Nothing worked.
The echo returns the correct value at the success function of $.post back at home.php .I tested it

But when i try to retrieve the $user1 from a different file i receive again a null/empty variable.

P.S. Dont patronize me about the sql injections and sanitize your data etc… my code is in a testing proccess. When it will work ill convert the sql to statements Work with me to make it work first

this is offtopic but still. There are no two separate processes," to make it work" and “to make it safe”. It is as ridiculous as to say, “first I want to walk, and I’ll breathe later”. The proper SQL interaction should be the natural part of the process, not some alien boring stuff that have to be added some day later. Otherwise it will do no good whatsoever.


So you are making two calls to chatusersquery.php, one with data properly set and one without sending any proper value?

1 Like

Yes the one is to send the value and the other call is to retrieve it only.The second call is from another file though. and it retrieves empty values as before.

p.s. xD I understand what you say about the security of my code but iam not familiar with the sql statements yet and i dont want to make aditional errors and don’t know where they come from. For now at least the code is simple without security

OK, that’s strange then. I extracted even less from your code and had this home page:

echo "<html><body>";
$uid = 5;
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$.post("chatuserquery.php", { user1:'<?php echo $uid; ?>', user2: 7},
   function(data){ alert(data);var timer = setTimeout(function()
   { window.location='chatuserhome.php' }, 2000);  });

and this very basic php code in chatuserquery.php


and I get exactly what I expected, which is a pop-up window containing the two post variables and their values. So I can’t provide any help on what might be causing that aspect of it to fail for you.

Presumably the missing quotes in these two lines are present in the live test code

$user1 = $_POST[user1];
$user2 = $_POST[user2];

Really? Did you notice my above comment?

Although it will trigger errors, it won’t affect the application logic

I did, but as the code is edited before going on the forum (for example, there’s talk of JSON-encoding the results but the code isn’t here) I just figured that other stuff was going on to continue to pass stuff around, or deal with it not being passed around. Given that the insert happens in the first call where the $_POST variables are passed through, I imagined some logic that made the PHP code call elsewhere (perhaps the code in the first example that gathers $log) if the $_POST array is empty.

Fair enough - I bothered to try it and saw error messages, but then didn’t notice that it had, in fact, created the $user variable.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.