mardi 24 mai 2016

PHP - How to insert/update values in database by clicking on a checkbox?

I have a script that successfully connects to database, fetches everything into $r array and then prints out in a HTML page.

My current database structure is:

DROP TABLE IF EXISTS `approvements`;
CREATE TABLE IF NOT EXISTS `approvements` (
`ip` int(10) unsigned NOT NULL DEFAULT '0',
`port_id` mediumint(8) unsigned NOT NULL DEFAULT '0',
`approved` int(1) unsigned NOT NULL DEFAULT '0'
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=0;
ALTER TABLE `approvements` ADD KEY `ip` (`ip`), ADD KEY `port_id` (`port_id`);

Part of my PHP code which is drawing checkbox and checks if it is checked currently looking like this:

<td class="protocol"><input type="checkbox" name="approved" id="approved" value="yes" <?php echo ($r['approved']==1 ? 'checked' : '');?>></td>

Everything works fine except one thing. I wanna set up a smart checkbox which (when user clicks on it) will insert a '1' value to table if entry not exists and update '0' to '1' or vice-versa if exists.

Currently it works the one way: when database entry field "approved" equals '1' then it is drawn checked on page, otherwise its unchecked. But when user clicks on this checkbox in browser nothing happens in a database.

So what do I need:

If entry not exists in table

INSERT INTO approvements (ip,port_id,approved) VALUES ($r['ip'],$r['id_port'],'(1 or 0'); *depends on user choice*

If entry exists in table

UPDATE approvements
SET approved=(1 or 0), *depends on user choice*
WHERE ip=$r['ip'] and port_id=$r['id_port']

Im a new one in PHP so any help from you will be appreciated. Thanks.




Aucun commentaire:

Enregistrer un commentaire