converting from array to string, implode didnt work - php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comp4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id , First_Name, Last_Name FROM member WHERE username='tracy'";
$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["First_Name"]. " " . $row["Last_Name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I have this code in order to display some details about a member in my database but I want to make it into a string and a variable, I tried to use the php implode function but I recieved an error saying that some of the other variables were unexpected any tips or anything wrong that im doing?

Where you used implode()
`<?php
$id = $row["id"];
$first_name = $row["First_Name"];
$arr=array ($id,$first_name);
echo implode(" ",$arr);
?>`

In your while loop, you should first concatenate all your column in one array, to be then collapsed in one single string as following :
while($row = $result->fetch_assoc())
{
// temp variables
$id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$array = array($id, $first_name, $last_name); // creating an array
$result = implode(" - ", $array); // Collapsing data using dash
printf($result); // displaying data collapsed
}
from official php implode doc

I you want the result in a string, replace the echo by this:
$results .= "id: " . $row["id"]. " - Name: " . $row["First_Name"]. " " . $row["Last_Name"]. "<br>";
Now everithing is in $results

Here is perfect solution for your problem.. It will work. i am using mysql extension rather than mysqli..

Related

how to php echo individual column values of a result row from mysql query?

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";
}

Displaying results of SQL query as a table?

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.

PHP Array ForEach SQL Query

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.

how to convert the text outputted from a database to links?

Iam class 11th..recently I started learning php and mysqliI have been facing a problem. I am trying to create a database which has a small list of movies.when the page loads, it displays the list of those movies from database..but the problem is, it displays them as a simple text..i Want them to be like links so that whenever it is clicked it displays the info about that particular movie..but i dont want to write anchor tag links for each movie..Is there any other way?
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, title FROM movies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
According to your code.
if ($result->num_rows > 0) {
$htmlLink = '';
while($row = $result->fetch_assoc()) {
$id = $row["id"];
$title = $row["title"];
$htmlLink .= "<a href='movie.php?{$id}'>id: {$id} - Name: {$title}</a><br>";
echo $htmlLink;
}
} else {
echo "0 results";
}
Then on your movie.php page use $_GET[] to get the query string data
Replace:
echo "id: " . $row["id"]. " - Name: " . $row["title"]. "<br>";
With:
$id = $row["id"];
$title = $row["title"];
echo "<a href='/movie/{$id}'>id: {$id} - Name: {$title}</a><br>";

Compare sql table with txt file line by line with table if variable dosent exsit insert it [closed]

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;
}
}
}
}

Categories