I am trying to use a FOREACH loop to query a database based on each value in the $userid array below. I am also looping through the $grade array as I need the corresponding value for the sql query to then put into a HTML table.
//Decode JSON file to an Object
$json_d = json_decode(file_get_contents("results.json"));
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table><tr><th>First Name </th><th>Last Name </th><th>Grade </th></tr>";
foreach($userid as $id) {
foreach($grade as $grd) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["firstname"]. "</td><td>" . $row["lastname"]. "</td><td> " . $grd . "</td></tr>";
}
} else {
echo "ERROR!";
}
}
}
echo "</table>";
mysqli_close($conn);
I have checked the $grade and $userid array and they do contain the correct values however running the PHP file I only get the first record outputted in the table. E.G.
FirstName LastName Grade
Student 1 85
Whereas I need the other 2 records that are supposed to appear.
Related
The below code works perfectly and gives me the "id" "firstname" and "lastname". What I want is to use a loop to echo all the field values in the result row without having to quote each column name like
$row["id"]
below is the working code
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " .
$row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
any thoughts please
This should work..
while($row = $result->fetch_array()) {
$i=0;
while($i<count($row)){
echo $row[$i];
$i++;
}
}
just use a foreach loop inside while like this
foreach($row as $key=>$value){
echo "<br> $key: ". $value. "<br>";
}
If I understand what you want to do is automate the output of the name of each column with its value (independent of the number of columns you get).
So do it like this :
if ($result->num_rows > 0) {
foreach($result->fetch_assoc() as $row) { // browse each records
foreach($row as $col => $value) { // browse each columns on a record
echo "<br>$col: $value<br>";
}
}
}
else {
echo "no result";
}
I am trying to output the results of an SQL query as a table on a page on my website. I have found a few solutions online but I can't get any of them to work properly. Right now I copied and pasted a bit of code to just output the first two columns but I can't figure out how to get every column in a table. I am new to PHP and web development in general so any help would be appreciated.
My PHP:
<?php
SESSION_START() ;
$servername = "localhost";
$username = "MY USERNAME";
$password = "MY PASSSWORD";
$dbname = "MY DATABASE NAME";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$_session['userid'] = $userlogged;
$sql = "SELECT * FROM `climbs` WHERE `userlogged` = '" . $_SESSION['userid'] . "'";
$result = mysqli_query($conn,$sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["climb-id"]. "</td><td>" . $row["climbname"]. " " . $row["cragname"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
check with var_dump :
some like that:
$result = mysqli_query($conn,$sql);
var_dump($result);
if ($result->num_rows > 0) {
maybe the query it's wrong.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
<?php
function db_query()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, alias, type, parent, ordering, published FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " alias" . $row["alias"]. " type: " . $row["type"]. " - parent: " . $row["parent"]. " ordering " . $row["ordering"]. "published " . $row["published"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
}
function read_location()
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "single4thenight";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name FROM iutca_jomcl_locations"; //selects locations from
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
// echo "Location : " . $row["name"]."<br>";
$row_name = $row["name"];
echo $row_name.'<br />';
}
}
$file1 = "./location.txt";
$lines = file($file1);
foreach($lines as $line_num => $line)
{
echo $line;
}
}
My location.txt file contains this
Auburn
Birmingham
Dothan
Gadsden
Huntsville
Mobile
Montgomery
Muscle Shoals
Tuscaloosa
I would like to compare my sql database with txt file to make sure that i do not arealdy have variables inside. I do not want to put duplicates in side my sql i would like to know what is the easiest way to update my sql
You could use INSERT IGNORE INTO instead of just INSERT INTO and MySQL will then ignore duplicate entries. See the MySQL documentation for INSERT for more information. So, based on what I see in your question, your SQL would look something like:
INSERT IGNORE INTO iutca_jomcl_locations ('name') values (?)
Hope this helps! :)
First we read file content to the $content variable
$content = file('mytxt.txt')
As you posted, your file contains words separated with space (if not, skip this and make variable $words contain values you need) so we need to split content, to get each word as array item
$words = explode(" ", $content);
Finally, inserting value and checking if there is one like that existing in DB
foreach($words as $word)
{
$sql = "INSERT iutca_jomcl_locations (name)
SELECT $word
WHERE NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE name = $word
);"
$result = $conn->query($sql);
}
iutca_jomcl_locations - table name
name - column to insert (also checking for unique values using this column)
I used This Code and it Worked for me
foreach($lines as $line_num => $line)
{
$line = $line;
//echo $line;
$sql = "SELECT ordering, name FROM iutca_jomcl_locations WHERE name='$line'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
echo "Found Locations: " . $row["name"]." The ordering Number Is " . $row["ordering"]."<br>";
$ordering =$row["ordering"];
}
} else {
if($ordering >=0)
{
$count = $ordering;
//echo "0 results";
$lowerCase = strtolower($line);
$sql = "INSERT INTO iutca_jomcl_locations (name, alias , parent, published,ordering)
VALUES ('$line','$lowerCase','$parent','1','$count')";
$count = $count + 1;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully <br />";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}
I need help on how to do this correctly. I need to execute this command:
SELECT concat(branchname, -->, itemtype, '(, quantity, ')') from monitoring
order by itemtype;
the syntax works in MySQL console. However, im having trouble with implementing it on php. I always get
"Undefined index: branchname"
"Undefined index: itemtype"
"Undefined index: quantity"
using this code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
The error says it's in this line
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
Im confused because I basically ran the same code that worked that lets me see the itemtype in the table:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemtype FROM monitoring";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "itemtype: " . $row["itemtype"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Help anyone?
It seems your query needs update
"SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
It should be
"SELECT branchname,itemtype,quantity from monitoring order by itemtype";
I have posted this answer in reference of how you were calling your fields in while loop
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
and if you need to show the concat value within one field than it should be something like
$sql = "SELECT concat(branchname,' ',itemtype,' ',quantity) as branch from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["branch"]."<br>";
}
} else {
echo "0 results";
}
Just define the alias for the concatenated columns. Use this -
SELECT concat(branchname,itemtype,quantity) as branchname from monitoring order by itemtype
Or if you want them seperately then -
SELECT branchname, itemtype, quantityfrom monitoring order by itemtype
The code below works fine. However I would like to output the results using a loop. I can do it by going through each key individually or as $post[0] for example but not using a loop to go through all the returned fields. All I get is one value of "Array". It looks like the entire array is inserted into a variable I'm not sure what's going on. I have tried http://www.hackingwithphp.com/5/3/0/the-two-ways-of-iterating-through-arrays. Any suggestions appreciated and also if anyone could explain what is going on that would be great. Thanks.
$ID = $_POST['ID'];
function query($ID){
$servername = "x.x.x.x";
$username = "xxxxx";
$password = "xxxxx";
$dbname = "xxxxx";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM GROUP WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_array($result)){
$resArr[] = $row;
}
return $resArr;
}
$person = query($ID);
foreach($person as $post) {
echo $post['ID'] . "<br>";
echo $post['NAME'] . "<br>";
echo $post['POSITION'] . "<br>";
echo $post['TELEPHONE_NUMBER'] . "<br>";
echo $post['EMAIL'] . "<br>";
}
?>
Its not totally clear what you are asking but I assume you want to loop through the individual fields of the selected rows. As you built an array containing the query results each result itself being an array mysqli_fetch_array($result) then you can just add an inner loop to process the individual row array like so :-
$persons = query($ID);
foreach($persons as $person) {
foreach ( $person as $fieldname => $value ) {
echo $fieldname . '-' . $value . "<br>";
}
}
Group is reserved word of mysql you can use it in backtics ``
$query = "SELECT ID, NAME, POSITION, TELEPHONE_NUMBER, EMAIL FROM `GROUP` WHERE ID = '$ID'";
$result = mysqli_query($conn, $sql);