I'm trying to fill in the different options on a form calling objects from a database using a different php file. Here is my code:
PHP Code (functions.php):
<?php /* Gets values from sql and inserts into html options values */
function selectOptions($column, $table){
// fetch records
$sql = "SELECT" . $column. "FROM" . $table. "ORDER BY Id";
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' .$row['$column']. '</option>';
}
}
else {
echo '<option>No results!</option>'; } } ?>
HTML code:
<?php
require "php/dbconnect.php";
require "php/functions.php";
?>
<select class="form-control">
<option>SUBJECT</option>
<?php
selectOptions("Subjects", "general_subjects");
?>
</select>
I use this function multiple times for different forms, so I figured having it in its own file would be the best approach but it does not work. When I use the function without variables inside the index.php file, it seems to work. I don't know what I am doing wrong
EDIT: Image of what it should be doing Image of index.php
Add spaces to your sql query. Also you need to access the $column variable properly. You shouldn't wrap it around single quotes as it is a variable. You also have a variable scope issue as $conn does not exist
function selectOptions($conn, $column, $table) {
// fetch records
$sql = "SELECT `" . $column . "` FROM `" . $table . "` ORDER BY Id"; #add spaces
$result = $conn->query($sql);
//check there are more than 0 rows
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option>' . $row[$column] . '</option>'; #remove single quotes
}
} else {
echo '<option>No results!</option>';
}
}
When you call the above function, add the echo keyword
<?php
echo selectOptions($conn, "Subjects", "general_subjects"); #echo the function
?>
Would you try editing your function.php sql part like this
$sql = "SELECT " . $column. " FROM " . $table. " ORDER BY Id";
i think the spaces is the reason that it's not returning data
Related
I have an query that shows data from db. I use while loop to display data. Problem is that I can call (echo) result only once.
Here is my code:
$ime_ = "SELECT * FROM `users` WHERE '" . ($_COOKIE['username']) . "' = user_username";
$ime_result = $mysqli->query($ime_);
and later in my html I use this result as:
<?php
if ($ime_result->num_rows > 0)
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
This work ok, but I want to use this result to display many times in my html. And when copy while loop again later in html no result is given.
Store the string with data from while() into a variable, than apply echo to that variable as many times as you like..
$re_out ='';
if($ime_result->num_rows > 0){
while($row = $ime_result->fetch_assoc()) {
$re_out .="<h2>". $row["Ime"] ."</h2>";
}
}
echo $re_out;
//etc..
echo $re_out;
<?php
if ($ime_result->num_rows > 0)
$ime_result->data_seek(0); // seek to row no. 1
while($row = $ime_result->fetch_assoc()) {
echo "<h2>" . $row["Ime"] . "</h2>";
}
?>
Haven't run script. Try if it works.
In my case, I am getting only the EmployeeId which i have registered latest and not all the employeeId's from the table in database.
Code :
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
**while ($row = $query->fetch_assoc()) {**
$id = $row["EmployeeId"];
$_SESSION["id"] = $id;
}
}
}
i am using this session value in tag in my html form.
<select name="EmployeeId" required autofocus class='form-control'>
<option value=""> ----Select----</option>
<?php
if (isset($_SESSION["id"])) {
echo "<option value = " . $_SESSION["id"] . ">" . $_SESSION["id"] . "</option>";
}
?>
</select>
Someone suggested me to check the array , but i am confused.
You're currently overwriting the ID on each iteration. You need to store them in an array in which you append each ID instead:
// Make this session item an array
$_SESSION['id'] = [];
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array
$_SESSION['id'][] = $row["EmployeeId"];
}
Now you need to iterate through the array with the ID's when printing the options:
if (isset($_SESSION["id"])) {
foreach ($_SESSION['id'] as $id) {
echo "<option value='$id'>$id</option>";
}
}
This should work, as long as you have session_start() in the top of your scripts.
I would probably not use sessions to store results like this, but I don't know enough of your code to be able to give you a good solution.
i thik the problem is that you should retrieve data in array from query and you can apply foreach loop to print the employee.
first get all the employee
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
$result = query($query);
now print the retrieved employee in option field
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row["id"] . ">" . $row["id"] . "</option>"
}
} else {
echo "<option value="">No result found.</option>"
}
For me wouldn't advise to use sessioning, then to populate your select input, you do the below code, this is just a method of doing this anyway
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
$ids = array();
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while($row = mysqli_fetch_array($query)){
$ids[] = $row['EmployeeId']; //we populate our array here
}
}
return $ids; //return the array here
}
from your html you do this
<select>
<option value="">Select</option>
<?php
$ids = getEmployeeId();
for($i=0;$i<count($ids); $i++){
?>
<option value="<?php echo $ids[$i];?>"><?php echo $ids[$i];?></option>
<?php }?>
</select>
It is because, you are putting only last value of array in $_SESSION["id"] variable
Change $_SESSION["id"] = $id; to $_SESSION["id"][] = $id;
and to print
if (isset($_SESSION["id"])) {
foreach($_SESSION["id"] as $v){
echo "<option value ='" . $v . "'>" . $v."</option>";
}
}
I'm trying to pull data from my DB to a html form, I have managed to so for a table in a while loop, but not for a form. Here is my code:
if(isset($_POST['search'])){
$quote = $_POST['quote'];
}
$stmt = "SELECT * FROM dbo.tblVersions2 WHERE QuoteNumber LIKE '".$quote."'";
$result = odbc_exec($conn, $stmt) or die('ODBC Error: ' . odbc_errormsg($conn) );
while (odbc_fetch_row($result)) // while there are rows
{
// What do i out here? I only know echo "<td>" . odbc_result($result, "QuoteNumber") . "</td>";
// which is to display tabular data, but how with a form??
}
?>
I've tried declaring a variable in the while loop, such as $Address1 = -'Address1]; then declaring in the form value=" but it doesn't seem to work, please help!
I have problem with my code.
I use nested while in my code and the nested while doesn't work, only the outer while is work
I don't know where is the bug of my code.
This is the piece of my code :
$database = new mysqli('127.0.0.1', 'user', 'user', 'mini_email');
$query = 'SELECT * FROM mails';
$query2 = 'SELECT * FROM users';
$result_set = $database->query($query);
$result2 = $database->query($query2);
while ($row2 = $result2->fetch_assoc()) {
if ($row2['username'] == $_SESSION['user']) {
$id_email = $row2['id'];
}
}
if (isset($_SESSION['is_logged_in'])) {
echo('<center><font size="10">Mailing List</font></center><br><br>');
echo('<center><table border="3" bgcolor="#f0cdfa">');
echo('<tr>');
echo ('<td>No</td>');
echo ('<td>ID</td>');
echo ('<td>From</td>');
echo('<td>Subject</td>');
echo ('<td>Message</td>');
echo ('<td>Action</td>');
echo ('</tr>');
$i = 1;
while ($row = $result_set->fetch_assoc()) {
if ($row['to_user_id'] == $id_email) {
echo('<tr>');
echo ('<td>' . $i . '</td>');
echo ('<td>' . $row['id'] . '</td>');
while($row2 = $result2->fetch_assoc()){
if($row2['id']== $row['from_user_id']){
echo ('<td>' . $row2['username'] . '</td>');
}
}
echo ('<td>' . $row['subject'] . '</td>');
echo ('<td>' . $row['message'] . '</td>');
echo ('<td>View</td>');
echo ('</tr>');
$i++;
}
}
Your initial
while ($row2 = $result2->fetch_assoc()) {
is looping through all the records to the end of the set,
so looping a second time won't retrieve any further records because you're already at the end of the resultset
Resultset pointers aren't automatically reset when you initiate a new loop, but you can reset them manually using
$result2->data_seek(0);
before each subsequent loop
But iterating the point made in the comments by #Sirko you'd be better using a JOIN to make a single query
If I may help, I think you shouldn't even perform the queries when your if statement with the session returns false.
In the first lines or your script you should define a function with all this code, and write it like this :
function YourFunction()
{
if (isset($_SESSION['is_logged_in'])) {
return false;
}
// Database connection and queries
// your business
}
This will be more clean.
Next, your query doesn't seem to be correct. You get all the mails of your website, and then in a loop you check if the mail user id is the user id you have in session. Imagine the lack of performance if you have 35 000 mails in your database.
Improve your query with a WHERE statement : http://www.w3schools.com/sql/sql_where.asp
then, are you sure that $_SESSION['user'] contains an id ? I think your second if statement never returns true because of that.
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php