Can not get correct value from SELECT

Hello guys!

I have this problem. On a one page I put value from input to div, and then send it via json, to another file, where I store it to the database.

On that first page (where I send data via JSON) I want to show that data from database. I am quering only the last entry. If the entry has ID = 30, I get ID 29. But when I refresh website, or do another entry, I get the value, but it is not the correct one.

I`ve tried with AUTOCOMMIT, doing timeout before quering data from database. Nothing helped. Can you point me to the answer?

Post your code.

Well, if you are calling out to a secondary page, you really do not know what the ID of the recently entered
data is. Normally you would use something like:
$new_id = mysqli_insert_id($db);
After you have run an INSERT query to insert data… My guess without seeing code, is that you are not
pulling the new id correctly.

As Kevin said, show us your code. Please make sure you place it inside of the PHP tags…

Hey guys.

I have tried with autocommit, with timeout. Can not get correct value of $telefonska_str

Here is the code:

Beware - button id=“button2” has jquery function behind:

<script type="text/javascript">
$(document).ready(function() {
console.log("document is ready!!!");

         $("#button2").click(function() {
           var telefonska_str = document.getElementById("telefonska_str").value;
             var jsonData = {};
             jsonData["telefonska_str"] = telefonska_str;

             console.log(telefonska_str);

           //  alert($(this).attr('lat'));
             $.ajax({
                 type: "POST",
                 url: 'validate_tel.php',
                 data: {data : JSON.stringify(jsonData)},
                 success: function(data) {
                   console.log(data);
                     alert(data);
                 }
             });
         });
     });
</script>

First page, where I get data and send it as json:

[php]

		Telefonska:
	         
	         
Znamka:
Lokacija:
Nadaljuj

<?php
$con=mysqli_connect("localhost", "", "", "");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql=“SELECT * FROM temp ORDER by id DESC limit 1”;

if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
else {
echo "Telefonska stranke: " . $result[1] . “\r\n”;
}
mysqli_close($con);
?>
[/php]

Here is the validate_tel.php

[php]

<?php header('Content-type: text/html; charset=utf-8'); /* validate_tel.php is invoked by ajax with json data (longitude and latitude stored in data). All return types should be echo(ed), so the javascript can read it back. */ // get data from ajax post method. $jsonData = json_decode(stripslashes($_POST['data'])); // Store lat and lon separately. $telefonska_str = $jsonData->telefonska_str; // Prepare SQL connection. $con = mysqli_connect("localhost","","",""); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); // abort? exit; } // escape variables for security // to prevent SQL injections. $telefonska_str = mysqli_real_escape_string($con, $telefonska_str); // Prepare sql statement $sql = "INSERT INTO temp (telefonska_str) VALUES ('$telefonska_str')"; // echo $sql; // Run the query. If query fails, bail. if (!mysqli_query($con, $sql)) { echo "Falied to execute SQL query with statement: " . $sql; exit; } ?>

[/php]

How I am trying to get telefonska_str:

[php]

<?php $con=mysqli_connect("localhost", "zzzzzzzzzz", "zzzzzzzzzz.", "zzzzzzzzz"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $sql="SELECT * FROM temp ORDER by id DESC limit 1"; if ($result=mysqli_query($con,$sql)) { // Fetch one and one row while ($row=mysqli_fetch_row($result)) { printf ("%s (%s)\n",$row[0],$row[1]); } // Free result set mysqli_free_result($result); } else { echo "Telefonska stranke: " . $result[1] . "\r\n"; } mysqli_close($con); ?>

[/php]

matej, I removed your connection string info so others will not see it. You should not post your userid or
password for your database! Anyone can read this site…

Well, to explain your problem. You have code which calls outside of itself to run an INSERT query. What this
means is that the current code does not see the updated database. Any previously completed queries are
still in tact. Sounds odd, but, lets explain…

When you run a query on the database, it retrieves a “RECORDSET” which is “fetched” by the MySQLi code
as needed. The recordset of the results from the query does not change and stays in tact. If you call
outside your code using JQuery and AJAX as you did, the current recordset does not change at all. Therefore,
your ID # 30 is there, but, NOT inside the current queried recordset. You would need to rerun the query
to “refresh” the data returned from the query. Since your call outside of the PHP code does not update the
inside current PHP variable for the recordset ( $result and $row ), your page does not see the newly
created ID number. Your “validate_tel.php” page inserts the new data, but, it does not refresh the “live”
data already in the page. You would have to re-query the database.

Hope that make sense…

[member=43746]ErnieAlex[/member], thank you - it must of slipped me.

Ok, I do understand what are you trying to say. Would it help if I hardcode refresh to validate.php?

Well, when you create an new row of data in your database using an INSERT query, it places it inside the
database. If you do this outside of the current PHP code using your JQuery code, it does put it in place.
But, you need to refresh the live queried data. Therefore, yes. Or, you can just make it redirect back to
the first page.

I am not clear on why you are using JQuery to insert records outside of the PHP code and not just using
PHP itself to do it. Normally, if you have a form that displays items in a database and have a “add new item”
section, you just post to the same page and let the PHP code handle the inserting. This allows for
refreshing the page automatically because it will insert the data and then redraw the list of items. Perhaps you can explain why you want to go outside the page to handle your insert? Usually if a programmer is using this form is to keep other items on the page while handling DB calls behind the scenes. But, your
code is simple and does not need this process.

I am not that familiar with PHP. I know that PHP is server side programming language, therefore it cannot read values from div`s, that is why I am pushing data via jQuery, which can get value.

Will try with refresh.

I see now. Well, normally, all data displayed is placed into a format that can be read back as needed.
Then, the PHP can read it using normal $_POST variables. If you need the server-side code to read an
entry in a DIV, just place a “HIDDEN” field inside the DIV that would hold the data and then PHP can read it.

matej, I have to leave for many hours, but wanted to mention a couple other issues with your code.

Normally, if you are using PHP to load data from the database and displaying it, you already have the data
usable from the variables. Therefore, you do not need to read data inside of a DIV as you already put that
info there using your PHP code. If you are using outside calls to load different DIV’s and want to pull that
data, then your page is not well formed. It would be better to just add more ways for the user to load
those DIV’s using buttons and process them SERVER-SIDE.

Also, if you use JQuery which is CLIENT-SIDE, a hacker can look at your code and find how you are calling
your outside code. This might allow a good hacker to INSERT their own data into your database and mess
it up. It just is not as secure as using SERVER-SIDE code.

Just my opinion, but, there are many ways to accomplish any project…

No, refresh does not work. I have set it up to reload every 0,03 second. Still do not get correct value on a query.

Code containing refresh on validate_tel.php

[php]

<?php header('Content-type: text/html; charset=utf-8'); /* validate_tel.php is invoked by ajax with json data (longitude and latitude stored in data). All return types should be echo(ed), so the javascript can read it back. */ // get data from ajax post method. $jsonData = json_decode(stripslashes($_POST['data'])); // Store lat and lon separately. $telefonska_str = $jsonData->telefonska_str; // Prepare SQL connection. $con = mysqli_connect("localhost","","",""); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); // abort? exit; } // escape variables for security // to prevent SQL injections. $telefonska_str = mysqli_real_escape_string($con, $telefonska_str); // Prepare sql statement $sql = "INSERT INTO temp (telefonska_str) VALUES ('$telefonska_str')"; // echo $sql; // Run the query. If query fails, bail. if (!mysqli_query($con, $sql)) { echo "Falied to execute SQL query with statement: " . $sql; exit; } mysqli_close($con); header("refresh: 0.03;"); ?>

[/php]

Thanks [member=43746]ErnieAlex[/member] will look into it more carefully. Thank you for your help, you`ve put me on a right track. Thanks… Will let you know how it worked out.

Isn’t the validate_tel.php file the one you are calling thru the outside call? If so, it can not refresh the live
page that calls it. You could make it redirect to the original page, but, again that is not the way to do this
type of code. I am leaving now. Will check in several hours from now…

Sponsor our Newsletter | Privacy Policy | Terms of Service