0

Hello I am trying to collect some data from data base, change the value and then insert new value back into data base but i cannot get it to work. At the moment a button is clicked that sends value 1 to this script. database value for for light1 is obtained. If Get received is = 1 then toggle light 1 and insert new value back into database. If I run this all separately i can receive the data, toggle the data and insert it. But it will not all run together on one page. What am i doing wrong.

<?php
// but GET value into variable;
$light1recieved = ($_GET['light1']);

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="14Odiham"; // Mysql password 
$db_name="sean"; // Database name 
$tbl_name = "lights";

// Connect to server and select database.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

//Retrieve all data from the table
$sql = "SELECT * FROM $tbl_name WHERE id = 1 LIMIT 1";
$result1 = mysql_query($sql, $link);

// if successfully, displays message "Successful". 
if($result1){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
while ($row = mysql_fetch_assoc($result)){
    $light1 = $row['light1'];
}

echo $light1;
if ($light1recieved == "1"){
    $light1 = !$light1;
}

// Insert data into mysql 
$sql = "UPDATE $tbl_name SET light1=$light1";
$result = mysql_query($sql);
if($result){
echo "Successful";
echo "<BR>";
}

else {
echo "ERROR";
}
echo $light1;
?>
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • 2
    you realize that without a `WHERE` clause for `UPDATE`, you're trying to update your entire db; probably the reason it's failing here. Checking for the real error will tell you that. `echo "ERROR";` did not help you, `mysql_error()` will. – Funk Forty Niner Mar 08 '17 at 21:29
  • and this part `$light1 = !$light1;` that second variable's a negation. – Funk Forty Niner Mar 08 '17 at 21:31
  • 3
    ***Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php).*** [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Mar 08 '17 at 21:37
  • 2
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Mar 08 '17 at 21:37

0 Answers0