It is required to enter data through a php script into the database table. To connect to the database, the connect.php file is used, to add data, add.php and the page where you can view the table with data is index.php. A database has been created on the server named database and a table in it named templog. There are no errors, but no data is added.

connect.php

<?php function Connection(){ $server="localhost"; $user="root"; $pass="123456"; $db="database"; $connection = mysqli_connect($server, $user, $pass); if (!$connection) { die('MySQL ERROR: ' . mysqli_error()); } mysqli_select_db($connection,$db ) or die( 'MySQL ERROR: '. mysqli_error() ); return $connection; }?> 

add.php

 <?php include("connect.php"); $link=Connection(); $temp1=$_POST['temp1']; $hum1=$_POST['hum1']; $query = "INSERT INTO `templog` (`temperature`, `humidity`) VALUES ('".$temp1."','".$hum1."')"; mysqli_query($link,$query); mysqli_close($link); header("Location: index.php");?> 

index.php

  <?php include("connect.php"); $link=Connection(); $result=mysqli_query($link,"SELECT * FROM `templog` ORDER BY `timeStamp` DESC"); ?> <html> <head> <title>Sensor Data</title> </head> <body> <h1>Temperature / moisture sensor readings</h1> <table border="1" cellspacing="1" cellpadding="1"> <tr> <td>&nbsp;Timestamp&nbsp;</td> <td>&nbsp;Temperature&nbsp;</td> <td>&nbsp;Moisture&nbsp;</td> </tr> <?php if($result!==FALSE){ while($row = mysqli_fetch_array($result)) { printf("<tr><td> &nbsp;%s </td><td> &nbsp;%s&nbsp; </td><td> &nbsp;%s&nbsp; </td></tr>", $row["timeStamp"], $row["temperature"], $row["humidity"]); } mysqli_free_result($result); mysqli_close($link); } ?> </table> </body> </html> 
  • for starters, it would be nice to see the result of mysqli_query, you see, and errors will appear - splash58

1 answer 1

After

 mysqli_query($link,$query); 

Do:

 var_dump(mysqli_error($link)); 

Maybe your table is not created. Or in another database is located. Your code is checked, although it is scary, it also works for index.php and add.php.

Make sure that the $ _POST parameters come in add.php .

  • The table created is located in the needed database. Here is the result of Notice: Undefined index: temp1 in D:\Server\htdocs\www\add.php on line 6 Notice: Undefined index: hum1 in D:\Server\htdocs\www\add.php on line 7 string(61) "Incorrect integer value: '' for column 'temperature' at row 1" - Stanislav
  • You see. 1) Temp1 and hum1 do not come to $_POST . Maybe you need to take from the $_GET parameter? 2) An empty line is trying to be inserted into the temperature field (because of item 1), and your field is declared as int - that is numeric In general, you need to look at why the parameters in add.php do not come. - jekaby
  • Exactly, fixed POST on GET and the data was added. Thank you) It is strange that the article uses POST and everything works. Thanks again. - Stanislav
  • @Stanislav if the answer suits you, you can tick it off) - jekaby