简体   繁体   中英

How to add javascript data to mysql?

I have problem how to add this javascript data to mysql database?

<script type="text/javascript">    
var count = 0;

function countClicks() {    
 count = count +1 ;    
    document.getElementById("likes").innerHTML = count;     
}    
</script>


<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>    
<div id="likes">0</div>

You need to use mysql-real-escape-string while inserting your js code to mysql db. Assign your code string to a variable and use mysql-real-escape-string while inserting db. Example usage;

HTML:

<form action="save_code.php" method="POST">
    <table>
    <tr>
        <td>Code</td>
        <td><textarea name="code"></textarea></td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="Save" value="Save"/></td>
    </tr>
    </table>
</form>

PHP: save_code.php

// Comment out this for real test
//$jsCode = $_POST['code'];

//Assign js code string to variable
$jsCode = '<script type="text/javascript">    
var count = 0;

function countClicks() {    
 count = count +1 ;    
    document.getElementById("likes").innerHTML = count;     
}    
</script>


<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>    
<div id="likes">0</div>';

$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    or die(mysql_error());

$query = "INSERT INTO your_table(id, code) VALUES('', mysql_real_escape_string($jsCode))";
mysql_query($query);

You have 2 ways to do:

1- AJAX

You must make a SaveData.php for example and make a ajax Post to this page and then insert in database.

2- JS to PHP

In the same page you do this

Insert into TABLE (count) VALUES (".<script> write(count); </script>.");

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