简体   繁体   中英

How to make php get last row from a Colum from mysql and make the result a variable that I can take with javascript?

I want php to get the last row of a specific Colum. Then I want the result to be a variable that javascript can take and have it a javascript variable.

something like this maybe

var result = [php variable]

My question is not just about how to make a php variable into javascript varibale but also on how to make php get the last row of a colum. Thanks, BTW (I'm new to this stuff so please be clear in your explainations.)

In order to get the last row of a specific colum , you need to query your database in a way such that your desired "last row colum value" is easily obtainable by php. This is commonly done using the SQL ORDER BY and LIMIT clauses.

For example:

SELECT name FROM my_table ORDER BY id DESC LIMIT 1;

This query's result-set will contain only the name column value for the my_table record with the highest id .

PHP can then assume that this data is contained by the first row in the result-set. For example (using PDOStatement ):

<?php
//...
$data = $pdoStatement->fetch(PDO::FETCH_ASSOC);
echo $data['name']; // The name column value of the row with the highest id

The specifics of the query for your use case are not made clear by your original post, but the above example logic should apply anyhow. Make sure you provide the appropriate query and have PHP fetch the first record in the result-set.

You can then parse this data into Javascript variables:

<?php
<script>
    var result = "<?php echo $data['name']; ?>";
</script>

Warning: This example is very basic, make sure you protect yourself against XSS vulnerabilities. Do not let database data provided by PHP be evaluated by Javascript without protection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM