Displaying ALL data from sql table in PHP? - php

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>

You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}

fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

Related

How to get SQL data to PHP array

I kinda messed up the title, but i will try to explain my problem. i have a html page called leden.html and have a PHP script on it which gets data from my database and creates a table on the html page. Now the part where i get stuck is showing if a member is online and if someone is online the $sql1= "ja" else $sql1= "nee", but i messed up somewhere because when two people are online, the last person who came online shows online and the first dude goes back to "nee". Here is the code, i think something goes wrong at the array part.
<?php
$conn = mysqli_connect("******", "******", "******", "******");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email FROM register";
$sessie_username = "SELECT username FROM sessie";
$result = $conn->query($sql);
$result1 = $conn->query($sessie_username);
$row1 = $result1->fetch_assoc();
$nameninsessie = array($row1["username"]);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (in_array($row["username"], $nameninsessie)) {
$sql1 = "Ja";
} else {
$sql1 = "Nee";
}
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"] . "</td>
<td>". $row["email"]. "</td><td>" . $sql1 . "</td></tr>";
}
echo "</table>";
} else { echo "0 resultaten"; }
$conn->close();
?>
You are only getting ONE of the logged in users from the sessie_username query. And also building the array of logged in users incorrectly. See below
<?php
$conn = mysqli_connect("******", "******", "******", "******");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email FROM register";
$sessie_username = "SELECT username FROM sessie";
$result = $conn->query($sql);
$result1 = $conn->query($sessie_username);
// initialise the array
$nameninsessie = array();
// loop over all logged in users
while ( $row1 = $result1->fetch_assoc() ) {
// add thir names to an array
$nameninsessie[] = $row1["username"];
}
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (in_array($row["username"], $nameninsessie)) {
$sql1 = "Ja";
} else {
$sql1 = "Nee";
}
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["username"] . "</td>
<td>". $row["email"]. "</td><td>" . $sql1 . "</td></tr>";
}
echo "</table>";
} else { echo "0 resultaten"; }
$conn->close();
?>
There is a problem in your data fetching. See the returning array using print_rcommand. You only get the first value of the sql query. So try this. Furthermore you have to initialize the array if not when there is 0 results for the mysql query it will give an error.
<?php
$conn = mysqli_connect("localhost", "root", "*****", "*****");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email FROM register";
$sessie_username = "SELECT username FROM sessie";
$result = $conn->query($sql);
$result1 = $conn->query($sessie_username);
$nameninsessie = array();
$i=0;
while($row1 = $result1->fetch_assoc()) {
$nameninsessie[$i] = $row1["username"];
$i++;
}
print_r($nameninsessie); //thi is to chek the array when problem solved please comment this line
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (in_array($row["username"], $nameninsessie)) {
$sql1 = "Ja";
} else {
$sql1 = "Nee";
}
echo "<tr><td>" . $row["id"]. "</td><td> " . $row["username"] . "</td>
<td>". $row["email"]. "</td><td> " . $sql1 . "<br></td></tr>";
}
echo "</table>";
} else { echo "0 resultaten"; }
$conn->close();
?>

PHP: Do not create a row if it already exists [duplicate]

This question already has answers here:
sql if in insert statement without select
(4 answers)
Closed 7 years ago.
I'm trying to create a row only if one doesn't already exist. I'm trying to check if a row exists with the same steamid, If it exists, do nothing. Otherwise create the row.
Using the following code creates a row everytime I refresh the page.
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Main WHERE steamid = ".$steamprofile[steamid];
//$sql = "SELECT setup FROM Main WHERE steamid = $steamprofile[steamid]";
$result = $conn->query($sql);
if(!isset($_SESSION['steamid'])) {
steamlogin(); //login button
} else {
include ('../core-auth/userInfo.php'); //To access the $steamprofile array
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (($row["setup"]) == 1){
echo "<br><div class='container'><div class='jumbotron'><div align='center'>";
echo "<h4>You have already Setup your account!</h4><br>";
echo "<a href='../index.php' class='btn btn-success btn-block' role='button'><span class=' glyphicon glyphicon-ok' aria-hidden='true'></span> Back</a>";
exit;
}
}
} else {
$sql = "INSERT INTO Main (steamname, steamid, warns, notifi, setup)
VALUES ('$steamprofile[personaname]', '$steamprofile[steamid]', '0', '0', '1')";
if ($conn->query($sql) === TRUE) {
echo "Added user account.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
You forgot to add single quotes to the array variables. Please try the following updated code:
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM Main WHERE steamid = ".$steamprofile['steamid'];
//$sql = "SELECT setup FROM Main WHERE steamid = $steamprofile[steamid]";
$result = $conn->query($sql);
if(!isset($_SESSION['steamid'])) {
steamlogin(); //login button
} else {
include ('../core-auth/userInfo.php'); //To access the $steamprofile array
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if (($row["setup"]) == 1){
echo "<br><div class='container'><div class='jumbotron'><div align='center'>";
echo "<h4>You have already Setup your account!</h4><br>";
echo "<a href='../index.php' class='btn btn-success btn-block' role='button'><span class=' glyphicon glyphicon-ok' aria-hidden='true'></span> Back</a>";
exit;
}
}
} else {
$sql = "INSERT INTO Main (steamname, steamid, warns, notifi, setup)
VALUES ('".$steamprofile['personaname']."', '".$steamprofile['steamid']."', '0', '0', '1')";
if ($conn->query($sql) === TRUE) {
echo "Added user account.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
$conn->close();
?>
Hope this will help you. :)

Is it possible to assign sql table value to a variable in php?

Basically what I want is to assign the value of a field in my database to an variable. Can it be done in an effective way?
I was thinking something like:
$sql2 = mysql_query("SELECT * FROM rom WHERE idrom = 101");
while ($row = mysql_fetch_array($sql2)) {
$rom1 = $row['idrom'];
$status = $row['status'];
echo $rom1;
echo $status;
}
But this doesn't echo anything.
Edit:
I have gotten a bit longer on the way, now I am looking for a simpler way to assign the values to variables. As we speak I only need 4 values, but this still doesn't look like a very good way to accomplish what I want. Any better suggestions?
Heres what I got now:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM rom WHERE idrom = 101";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$room101 = $row["idrom"];
$status101 = $row["status"];
echo "This is roomnumber ". $room101 . "!<br >";
echo "And the status of roomnumber ". $room101 ." is ". $status101 ."<br><br>";
}
} else {
echo "0 results";
}
$sql2 = "SELECT * FROM rom WHERE idrom = 102";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$room102 = $row["idrom"];
$status102 = $row["status"];
echo "This is roomnumber ". $room102 . "!<br >";
echo "And the status of roomnumber ". $room102 ." is ". $status102 ."<br><br>";
}
} else {
echo "0 results";
}
You can use bind_result to do that.
Please try this simple example, hope it run well :
$mysqli = mysqli_connect('host', 'user', 'pass','dbase')or die('Could not connect: ' . mysqli_error());
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Because you provide an Id in where clause, you can use it for the new variable
$output = array();
$id = 101;
$sql = "select idrom,status from rom where idrom=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$id);
$stmt->execute();
if ($stmt->errno == 0) {
$stmt->store_result();
// $stmt->bind_result($idrom,$status); // way 1
$stmt->bind_result($output[$id],$output["status".$id]); // way 2
while ($stmt->fetch()) {
echo $output[$id]." -> ".$output["status".$id]."<br />"; // So, your output variable will be like $output[101] for way 2
// or you defined it here like :
// $output[$idrom] = $idrom;
// $output["status".$idrom] = $status; // For way 1
}
} else {
return "Error: " . $sql . "<br>" . $stmt->error;
}
$stmt->close();
$mysqli->close();

Is it possible to have a pull down menu to have an item selected in its list show if database already has information in it?

Version 4:
I have taken away the pull down menu for now, I just want the info to be posting correctly.
As it shows with the first line fab1 shows #2, in the second line it shows 1, --None-- instead of 2, Andy Khal. If anyone can figure out why, it be appreciated. I've done about as much as I can to figure this out and I'm lost.
<?php
// Connect to the database.
require_once('tb/connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("MySQL failed to connect: " . mysqli_connect_error());
}
// Create the SQL query
$testbed = "SELECT * FROM testbed";
$user = "SELECT * FROM user";
// Execute the SQL query and store the result set in
// the $result variable.
$testbed = mysqli_query($dbc, $testbed) or die("Failed to execute query on tesbed table: " . mysqli_error($dbc));
$user = mysqli_query($dbc, $user) or die("Failed to execute query on user table: " . mysqli_error($dbc));
// Read the results.
$row = mysqli_fetch_assoc($testbed);
if(!$row)
{
echo 'Query failed<br />';
}
else
{
echo "Query for Testbed Fabricator is : " . $row["fab1"] . "<br />";
}
$row = mysqli_fetch_assoc($user);
if(!$row)
{
echo 'Query for Testbed Fabricator failed<br />';
}
else
{
echo "Query for User ID # is : " . $row["userid"], $row["user"] . "<br />";
}
// Free the result set.
mysqli_free_result($testbed);
mysqli_free_result($user);
?>
Yes it is. You can specify the selected value with the selected keyword as a html attribute.
<option value="Username" selected>Username</option>
That makes this:
while($row = $result->fetch_assoc())
{
$user = $row['user'];
echo '<option value="' . $user . '"';
if($user is known)
{
echo ' selected';
}
echo '>' . $user . '</option>\n';
}
Update
In this snipped $choosen is the selected user's name.
echo'<div id="fab1">';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$mysqli->select_db('user');
$result = $mysqli->query("SELECT * FROM user");
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
echo '<option value="' . $row['user'] . '"';
if($row['user'] == $choosen)
{
echo ' selected';
}
echo '>' . $row['user'] . '</option>\n';
}
echo "</select>\n";
echo '</div>';

Mixing html with php search results?

I am trying to make the different the different rows have line breaks but its not working.
How is this done!? Please check my code below
Thanks guys!
James
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
{
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
}
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '$search%' AND lastname LIKE '$searchterm'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
}
mysql_free_result($result);
?>
<?php echo $row["name"];?>
<br>
<?php echo $row["lastname"];?>
<br>
<?php echo $row["email"];?>
Beats me what you find so hard about it:
while ($row = mysql_fetch_array(...)) {
echo ...
echo '<br>';
}

Categories