How to use PHP variable in Javascript?

前端 未结 5 1291
遇见更好的自我
遇见更好的自我 2021-01-22 23:18

I know you can\'t directly use PHP variables inside javascript code, but is there a way around it? I need to use these parameter\'s in javascript:

username: \'&l         


        
相关标签:
5条回答
  • 2021-01-22 23:19

    If you have selected only one column (and expect 1 row), you can use:

    $user_id = mysql_result($user_id, 0);
    

    which would fetch the 1st column of the 1st row of the result set $user_id.

    But for clarity's sake you should rename the variable $user_id, because it's not an ID but a resource (so call it $userQuery or something =)).

    0 讨论(0)
  • 2021-01-22 23:32

    I'm a little rusty on PHP, but this may work:

    <? //start HTML/Javascript code... 
        echo'var variable = ' . $user_id . '.example.co.uk';
        //finish HTML/Javascript here..
    ?>
    
    0 讨论(0)
  • 2021-01-22 23:33

    You can assign that php value in any html object then you use the object value in js page

    for example

    PHP:

    $phpvalue = $_GET["sid"];
    

    HTML:

    <input type="text" value="<?php echo $phpvalue ;?>" id="txtsamp" />
    

    JS:

    var phpval = document.getElementById('txtsamp').value;
    
    0 讨论(0)
  • 2021-01-22 23:34

    You can't use the result of a mysql_query() directly. Instead, you have to use mysql_result() or something similar (depending on your SQL query).

    0 讨论(0)
  • 2021-01-22 23:38

    Resource id #4 means u have just not complete the mysql query

    mysql_query returns Resource id

    u have to fetch the data using while ($row=mysql_fetch_array()) and then use

    written here

    For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

    For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

    UPDATE

    don't use mysql_real_escape string for GET data..instead use (int)$_GET['id']

    see here

    If no connection is found or established, an E_WARNING level error is generated

    0 讨论(0)
提交回复
热议问题