PHP / MySQL: How to store Select results in array - php

I am new to PHP and MySQL and hope someone can help me with this.
I have a MySql db with a table "TranslationsMain" and the following PHP query.
This returns all the items from column "German" (incl. the corresponding ID) from the db table and works correctly so far.
Instead of echoing the whole list (I just did this here for testing), **how can I store the results in an array in a way that each item within the array is stored with its value and a unique ID + how I can I echo specific items from this array by referring to their ID ?
Example:
I would like to echo the item value for ID "xyz" from this array (without calling the db again since this will be needed for multiple items on the page).
My PHP:
<?php
require_once("includes/header.php");
$tblTranslations = "TranslationsMain";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM " . $tblTranslations;
$translations = $conn->query($sql);
// for testing only
if($translations->num_rows > 0){
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
}
echo "</table>";
}else{
echo "0 results";
}
$conn->close();
?>
Update:
What I am looking for here is how to create a two dimensional array and how to fetch from it.
Many thanks in advance,
Mike

if($translations->num_rows > 0){
$result_arr = array();
echo "<table><tr><th>ID</th><th>Translation</th></tr>";
while($translation = $translations->fetch_assoc()){
echo "<tr><td>" . $translation["ID"] . "</td><td>" . $translation["German"] . "</td></tr>";
$result_arr[] = $translation;
}
echo "</table>";
}else{
echo "0 results";
}
// now you can iterate $result_arr
foreach($result_arr as $row){
echo "<tr><td>" . $row["ID"] . "</td><td>" . $row["German"] . "</td></tr>";
}

Related

How to update a specific sql row from a html table

So I have a HTML table that grabs SQL data and shows the data in the HTML table. I have a button in the HTML table aswell witch reredicts to update.php. Here I want the row that the user pressed the button in updates the column "paid" to "Paid". Screenshot of the HTML table: https://emildeveloping.com/screenshots/outredden-pardonableness-amharic.png
The thing is that I can't get it working that it updates just that specific row, it updates all rows right now.
Ive tried searching around for same questions but haven't found any solutions.
This is the PHP code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "emildeveloping2";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE purchases SET paid='Paid'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This is the PHP snippet of the HTML Table
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='purchases' class='purchases'><tr class='header'><th>Invoice ID</th><th>Customer ID</th><th>Product</th><th>Name</th><th>Email</th><th>Adress</th><th>Security Number</th><th>City</th><th>Zip Code</th><th>Country</th><th>Cost</th><th>Payment Plan</th><th>Status</th><th>Options</th></tr>";
// Visa datan
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["customerid"]. "</td><td>" . $row["product"]. "</td><td>" . $row["name"]. "</td><td>" . $row["email"]. "</td><td>" . $row["adress"]. "</td><td>" . $row["securitynumber"]. "</td><td>" . $row["city"]. "</td><td>" . $row["zipcode"]. "</td><td>" . $row["country"]. "</td><td>" . $row["cost"]. "</td><td>" . $row["paymentplan"]. "</td><td>" . $row["paid"]. "</td><td><a class='fas fa-check-square' href='update.php'></a></td></tr>";
}
echo "</table>";
} else {
echo "There is no active calls.";
}
I want just a specific row to update where id = id.
You need to update two things:
Add the id of the row you want to update as a GET argument in the link so it is passed to PHP script:
<a class='fas fa-check-square' href='update.php?row_id='.$row["id"].'>
Now if you check the links, each of them should be unique: update.php?row_id=1, update.php?row_id=2, etc.
Handle this added url parameter in the PHP script so it is used to select desired
row in database table:
$sql = "UPDATE purchases SET paid='Paid' WHERE id=".$_GET['row_id'];
If you get it working use http://php.net/manual/en/mysqli.prepare.php prepare method instead of query, so your code is not prone to sql injecton.
Something like this:
$mysqli->prepare("UPDATE purchases SET paid='Paid' WHERE id=?")) {
$stmt->bind_param("i", $_GET['row_id']);
$stmt->execute();
Another thing would be using POST requests instead of GET links to prevent CSRF vulnerability.

Why does a PHP file not get included in the file when run by the server?

I have one file called showRelayTeams.php and another called databaseSELECTOperation.php
I am trying to put the one with the database function into the one called showRelayTeams.php
showRelayTeam.php
<?php
$House = $_GET['q'];
$Data = "No Data";
$Query = "SELECT Firstname, Lastname, AgeGroup, Event, Value FROM tblEventEntries WHERE House = '" . $House . "' ORDER BY Value ASC;";
require("http://127.0.0.1/phpscripts/databaseOperations.php");
$Data = databaseSELECTOperation($Query);
$Counter = 0;
if (mysqli_num_rows($Data) > 0) {
echo "<table>";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Age Group</th>";
echo "<th>Event</th>";
echo "<th>Time</th>";
echo "<th>Select?</th>";
echo "</tr>";
while ($Row = mysqli_fetch_assoc($Data)) {
$Counter++;
echo "<tr>";
echo "<td>" . $Row["Firstname"] . " " . $Row["Lastname"] . "</td>";
echo "<td>" . $Row["AgeGroup"] . "</td>";
echo "<td>" . $Row["Event"] . "</td>";
echo "<td>" . $Row["Value"] . "</td>";
echo "<td><input type='checkbox' id='" . $Counter . "'
onclick='boxChecked(this.id)'></td>";
echo "</tr>";
}
}
echo "</table>";
?>
databaseSELECTOperation.php
<?php
//use the SQL SELECT command and return the data
function databaseSELECTOperation($Query) {
//this file will include the host, username, password and the database name
include "http://127.0.0.1/includes/variables.php";
//start a connection to the database using the credentials
$Connection = mysqli_connect($DatabaseHost, $Username, $Password, $DatabaseName);
//if the connection to the database was not successfully made then
if (!$Connection) {
//end the script and then print an error
die("Could not connect to the database: " . mysqli_error());
} //end if
//run the query and put the data returned in to a variable
$DataReturned = mysqli_query($Connection, $Query);
//return the data to the script that called it
return $DataReturned;
}
?>
I get the following error:
Fatal error: Uncaught Error: Call to undefined function databaseSELECTOperation()
When I insert the following code just after the require statement, I get
function not found
<?php
if (function_exists('databaseSELECTOperation')) {
echo "function found.<br />\n";
} else {
echo "function not found<br />\n";
}
?>
Any ideas on how to solve this?
That is the error:
require("http://127.0.0.1/phpscripts/databaseOperations.php");
When you are referring to the file via URL, it is including the output which is already processed by a web server, while you need to include the source PHP code.
Instead, you need to specify the path to the file on the file system like in the following examples:
require('../phpscripts/databaseOperations.php');
require('/var/www/html/phpscripts/databaseOperations.php');
require('C:\inetpub\html\phpscripts\databaseOperations.php');

PHP notice, returning "array array array" instead of values

Finally jumping into some PHP for the first time and I've written this program and i'm stuck. I've searched all over the place for about 2 hours to find a solution.
Basically I'm connecting to my local database and trying to grab all the rows from my 'songs' table, and display them by their names. Instead of getting their names, i'm getting a notice that says "Notice: Array to string conversion in C:\xampp\htdocs\musiclibrary\index.php on line 47"
My current output looks like this:
Title Artist Genre
Array Array Array
Array Array Array
Array
And then my code is...
<?php
// Require configuration file
require_once 'config.php';
// Connect to the database
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
// Check for database connection error
if(!$db_server)
{
die("Unable to connect to MySQL: " . mysql_error());
}
// Select a database
// The mysqli_select_db() function is used to change the default database for the connection.
mysqli_select_db($db_server, $db_database);
$prompt = array('Story title', 'Time', 'Person');
$prompt = array('Story title', 'Time', 'Person');
// Page title
echo "<h1>My Music Collection</h1>";
// Get music collection
$query = "SELECT * FROM songs";
$result = mysqli_query($db_server, $query);
$rows = mysqli_num_rows($result);
// If rows exist
if($rows > 0)
{
// Create HTML table
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
for($j = 0; $j < $rows; $j++)
{
// Build HTML table row
//PROBLEM LIES HERE ON THESE MYSQL_FETCH_ASSOC PARTS
echo "<tr>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'title') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'artist') . "</td>";
echo "<td>" . mysqli_fetch_assoc($result,$j,'genre') . "</td>";
echo "</tr>";
}
echo "</table>";
}
// If there are no songs in the database table
else
{
echo "There are currently no songs on file.";
}
?>
Any solutions to output the names of the rows in my database? Thanks!
Use the code below to replace your code
extract the values to an array first
show the values in table row
$values = mysqli_fetch_assoc($result);
echo "<tr>";
echo "<td>" . $values ['title']. "</td>";
echo "<td>" . $values ['artist'] . "</td>";
echo "<td>" . $values ['genre')]. "</td>";
You need to loop the mysqli_fetch_assoc function to count row then loop the row result to get value
Here is the code :
if($rows > 0){
echo "<table>";
echo "<tr><th>Title</th><th>Artist</th><th>Genre</th></tr>";
// Loop through each row in the database table
while($row = $result->mysqli_fetch_assoc()){
echo "<tr>";
foreach($row as $key => $value){
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
Hope it helps!
mysqli_fetch_assoc() function accepts only one parameter.
array mysqli_fetch_assoc ( mysqli_result $result )
Correct way to do this would be:
$query = "SELECT * FROM songs";
if ($result = mysqli_query($db_server, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . $row['artist'] . "</td>";
echo "<td>" . $row['genre'] . "</td>";
echo "</tr>";
}
mysqli_free_result($result);
}

PHP download a specific row from database table

I'm learning PHP right now and connecting to MySQL. I'm able to connect to a table called "info" and display the "date", "time", and "data" of each row, along with 2 extra columns that will allow the user to download the respective "data" into a txt and csv. This is where I'm completely lost on how to achieve that.
My understanding is that since it'll be a clickable link, I will have to use "href=" and will link that to a separate php that I create that will download that row's data, right? But then how does that new php file know which row to download from? I'm guessing I need to pass the row number it is to the other file?
Greatly appreciate it if anyone can lead me in the right direction or have examples. Thanks!
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT date, time, data FROM info";
$result = $conn->query($sql);
echo "<table border='1'>";
echo "<tr><td> Date </td><td>Time</td><td>Data</td><td> Download text </td><td> Download csv</td>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" . $row["time"]. "</td><td>" .$row["data"] ."</td><td><a href='NEEDTXTFILE.php'>".$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
echo "</tr>";
echo "</table>";
} else {
echo "0 results";
}
Assuming you select also the id value
$sql = "SELECT id, date, time, data FROM info";
....
you could add the id to your href eg:
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["date"]. "</td><td>" .
$row["time"]. "</td><td>" .
$row["data"] .
"</td><td><a href='NEEDTXTFILE.php?id=" . $row["id"] . "'>".
$row["date"].'.txt'. "</a></td>"."<td><a href='NEEDCSVFILE.php'>".
$row["date"].'.csv'. "</a></td> ";
echo "</tr>";
}
then in your NEEDTXTFILE.php you can obtain the id in $_GET['id']

Making SQL query from php and showing to HTML

I tailored this page mysql.php but for the time being it appears blank-white on the browser.
<html>
<head>
<title> MySQL Test </title>
</head>
<body>
<?php
$username = "username";
$password = "pass";
$hostname = "localhost";
$dbname = "StudentLessons";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password, $dbname)
or die("Unable to connect to MySQL");
echo "Connected to MySQL <br>";
$query = "SELECT * FROM Teacher GROUP BY bathmida";
$result = mysql_query($query);
echo "<table>"; // start table in html
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . row['onoma'] . "</td><td>" . row['epitheto'] "</td><td>" . row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
echo "</table>"; //close table
mysql_close(); //close the db connection
?>
</body>
</html>
Now I know for a fact that
The connection is legit.
The query is working because I tested them both.
I also advised another question here on [so] and it seems I am missing something important. The <tr><td> tags in HTML are set as they should be, so what might be the problem?
By the way, isn't there any other way to automate the process a bit? i.e. to develop a form that can support more queries etc.?
You forgot to add $ in below code
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . row['onoma'] . "</td><td>" . row['epitheto'] "</td><td>" . row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
correct code is:
while($row = mysql_fetch_array($result)) { //loop through results
echo "<tr><td>" . $row['onoma'] . "</td><td>" . $row['epitheto'] "</td><td>" . $row['bathmida'] "</td></tr>"; //$row['index'] is a filed name
}
You miss $, and you must use like this : $row->onoma
echo "<tr><td>" . $row->onoma . "</td><td>" . $row->epitheto"</td></tr>

Categories