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

For Loops in PHP Forum

View Course » View Exercise

0 points
Submitted by
almost 4 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:


$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");

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


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.

1771 points
Submitted by
Murray Moffatt
over 3 years ago