This forum is now read-only. Please use our new forums at discuss.codecademy.com.

For Loops in PHP Forum

View Course » View Exercise

0 points
3af0210b830b9ec9b56a61049b75a2b0?s=140&d=retro
Submitted by
즙쎰
about 3 years ago

Save to mysql and show text while typing onkeypress

The idea is simple. A key you press (a letter) appears in updated page:

keyj.php:


document.getElementById('k').onkeypress=function()
{
<?php
$db=new PDO('mysql:host=localhost;dbname=test;charset=utf8','$us','$ps');
$db->exec("UPDATE TXT SET texts=k.value");
$rl=$db->query("SELECT texts FROM TXT");
print_r($rl->fetchColumn());
?>
}

The intention is to have text on the screen via print_r. I successfully used it in another php to exchange information with MySQL and users screen (worked).
Here - the more you type and the more k.value is the more text will be on screen (just from server).

Unfortunately something went wrong.


0 votes

permalink

You can't mix PHP with Javascript like that!

The PHP code gets executed on the server before the page is sent to the browser. The output of the page, after the PHP has run, gets sent to the server. Then your Javascript kicks in and starts running.

What you could do is use AJAX in the Javascript to send the keypress to a PHP script on the server, which could then save the keypress in the database, and then the Javascript displays the keypress character.

However updating the database in this manner for every single keypress seems like overkill and could be quite slow. If you had many people running this page at the same time then your poor database might grind to a halt.

1390 points
5424d47f631fe9b0f6000d40_888624674
Submitted by
Murray Moffatt
over 2 years ago