So i recently set up a local web server on Raspberry Pi and I am currently experiencing little bit of trouble. I wrote a code (for test reasons) that after you click on one button in .html it runs test.php document that creates a table in sql, fills in the data and than prints the output.
<?php $conn= mysqli_connect('localhost','admin','admin','database_test'); $createTable='CREATE TABLE Bank_statements( id INT(3) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstName VARCHAR(15) NOT NULL, lastName VARCHAR(15) NOT NULL );'; $addData='INSERT INTO Bank_statements(firstName,lastName) VALUES ("peter","zupanc");'; $query='SELECT * FROM Bank_statements;'; $result=mysqli_query($conn,$query); if (isset($_POST['submit'])){ if (mysqli_query($conn,$createTable)){ echo 'sucess creating a table'; if (mysqli_query($conn,$addData)){ echo 'sucess adding data <br>'; while ($row=mysqli_fetch_array($result)){ echo $row['id'].$row['firstName'].$row['lastName']."<br>"; } }else{ echo 'error adding data<br>'.mysqli_error($conn); } }else{ echo 'failed at creating table:<br>'.mysqli_error($conn); } } mysqli_close($conn); ?>
Everything goes as planed till part when php should return/echo $row but it doesn’t its just empty space.
Advertisement
Answer
I believe your issue is that you executed $result=mysqli_query($conn,$query);
before the table was created in the DB.
The query is executed when you call it. The mysqli_fetch_array
just “transforms” a previous result row to an array format.
Try executing mysqli_query($conn,$query)
right before the while
.
I suggest also you define value for the mysqli_fetch_array
second argument $resulttype
(optional).
See docs for reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Default value (MYSQLI_BOTH
) is usually an overkill and apparently you just want the result format that comes from using MYSQLI_ASSOC
.