Ways of importing data from databases - php

I'm creating a web app which displays datas contained in a database.
I wrote the code and the app works, at least whith basic functions.
I'm already thinking about the future and that's why I'm asking for your help.
In case I will change the name of database's columns or maybe adding some new columns I will have to modify every single page of my code, if I want them to be shown in my web app.
For this reason I'd like to ask you if it is possible to write the columns name I want to import in a text file and then call this file to define which database's columns should be displayed on the net.
I'm attaching you the code I have write now so that you can understand better the part I want to change (which is the one of the 'while loop').
<html>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div id="holder">
<h1><?php echo "<font face=verdana size=30 color=#036>CAMBIO AMINOACIDICO</font>";?></h1></div>
<br>
<div id="sidebar" style="width:90%" class="sidebar">
NUOVA RICERCA
&nbsp |
RICERCA PER PAZIENTE
&nbsp |
RICERCA PER GENE
&nbsp |
RICERCA PER VARIANTE
&nbsp |
HOME
<P> </P>
</div>
<div class="container">
<?php
$conn= mysql_connect("loc", "db", "pss");
if (!$conn)
{
die("Connessione non riuscita <br>" . mysql_error());
//}else{
//echo "Connessione al database stabilita con successo<br><br>";
}
mysql_select_db("variant_db", $conn);
if(isset($_POST["vai"])){
$aa=$_POST["aa"];
}
echo "Verranno visualizzate le varianti per il seguente cambio di aminoacido:'<b>$aa</b>'.";?>
<br /><br />
<?php
$sql="SELECT A.AAchange, V.dnaCode, V.Chr, A.Start, A.End, A.Alt, A.Ref, V.zygosity, A.gene FROM annotazioni as A JOIN variante as V ON V.Start = A.Start AND V.Alt=A.Alt AND V.Ref=A.Ref WHERE A.AAchange='$aa'";
$result_dna = mysql_query($sql, $conn) or die(mysql_error());
if(mysql_num_rows($result_dna) == 0)
{
echo "<br>La ricerca non ha prodotto alcun risultato!<br>";
echo"<b>Effettuare una nuova ricerca.</b><br><br>";
}else
{?>
<div class="row">
<div class="col-mid-8 col-mid-offset-2">
<table id="table_var" "width=100%" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>AAchange</th>
<th>dnaCode</th>
<th>Chr</th>
<th>Start</th>
<th>End</th>
<th>Alt</th>
<th>Ref</th>
<th>Zigosity</th>
<th>Gene</th>
</tr>
</thead>
<tbody>
<?PHP
while ($record_dna=mysql_fetch_array($result_dna)){
echo '
<tr>
<td>'.$record_dna['AAchange'].'</td>
<td>'.$record_dna['dnaCode'].'</td>
<td>'.$record_dna['Chr'].'</td>
<td>'.$record_dna['Start'].'</td>
<td>'.$record_dna['End'].'</td>
<td>'.$record_dna['Alt'].'</td>
<td>'.$record_dna['Ref'].'</td>
<td>'.$record_dna['zygosity'].'</td>
<td>'.$record_dna['gene'].'</td>
</tr>
';
}
};?>
</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script>
<script type="text/javascript" src="js/ddtf.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" >
$('#table_var').ddTableFilter();
</script>
</body>
</html>

Keeping table names in txt or xml doesn't really solve anything and brings too much extra code.
For Examle say you have a table Z that has colums A, B C. And you have a piece of code that looks like SELECT A, B, C FROM Z. And you have some php logic after that.
FIRST EXAMPLE
You decided that you need to add column D to your table Z.
FIRST QUESTION
Will you need to select the data from the column D?
FIRST PROBLEM
If you need to select and process the data from column D, changing SELECT A, B, C FROM Z to SELECT A, B, C, D FROM Z probably won't be enough because you did not have any php logic that processed D before that, and you have to add it now. - Lots of extra code of controlling execution logic.
SECOND EXAMPLE
You decided that you don't need data column C in your table Z and you want do delete the whole column.
SECOCD PROBLEM
Here, changing SELECT A, B, C FROM Z to SELECT A, B FROM Z is 100% not enough.
You had some php code that proccesed data from C column, but now you have no C column, and the code must be removed. Also lots of extra code of controlling execution logic.
THIRD EXAMPLE
Your boss suddenly told you to add colunm N and you had no prior knolwedge that this will happen.
THIRD PROBLEM
You could'n have forseen it in any way, so in no way you could make all the needed extra code earlier. You still have to do everything manually.
All the examples above a ment to show, that you even if you add the code for controlling execution logic, in general you cannot predict what changes the structure might get.
All the extra code looses it's value, because you made a change that you did not forsee, and besides re-writing original logic, you also have to re-write the whole code for extra logic now.
Combining everything above, developing the code comes with the risk of having to re-write it, if and when some major structure changes occur.
I hope it was somewhat informative.

Related

Dynamic pages / menu in php

Hi I am working on some sort of a CMS page and I want to show on the /index.php page a list of all articles availble like /index.php?p=Art1.
And I have no clue on how to do that.
Any help is appreciated.
This is my index.php code:
<html>
<head>
<link rel="stylesheet" href="css/login-layout.css">
</head>
<body>
<div class="dialog-box">
<h2 style="font-size: 200%;margin-bottom: 0;">Pagini Noi</h2>
<h3 style="text-align: right; font-size:100%;margin-top: 0;">Logheazate pentru a edita paginile</h3>
<div class="pages">
<!-- Pagini \/ -->
<?php
include('config.php');
?>
</div>
</div>
</body>
</html>
Config.php contains the connection to the database $db is the variable name that i use.
The /index.php?p=Art1 method is actually a $_GET that you need to fetch. In your current example you would do:
$p = $_GET['p'];
Which if you would later echo:
echo $p;
you would get
Art1
but even before that, you should provide us with some database query example that you wish to do so we could show you how variable $p is passed on to a query that then selects the wanted rows from the table in your database. For simple mysql query you can check here: https://www.w3schools.com/php/func_mysqli_query.asp
WARNING: be sure to use mysqli_real_escape_string($p) in order to get a minimum protection from SQL injections.

Erased images shown if php head program file executes

This is head file of my program:
<?php
$obrazki = array('opona1.jpg', 'olej1.jpg', 'swieca_zaplonowa1.jpg',
'drzwi1.jpg', 'kierownica1.jpg',
'termostat1.jpg', 'wycieraczka1.jpg',
'uszczelka1.jpg', 'hamulec1.jpg');
shuffle($obrazki);
?>
<html>
<head>
<title>Czesci samochodowe Janka </title>
</head>
<body>
</br>
<h1 style="color:blue;font-size: 4em; text-align:center"> Czesci samochodowe Janka</h1>
</br>
<h3 style="color:red;font-size: 2em; text-align:center"> Witamy na stronie Czesci samochodowe Janka!</h3>
<form action="glowna.php" method=post>
<div align="center">
<table width = 100%>
<tr>
<?php
for ($i = 0; $i < 4; $i++) {
echo "<td align=\"center\"><img src=\"";
echo $obrazki[$i];
echo "\"/></td>";
}
?>
</tr>
<table>
</br>
<p style="color:red;font-weight:bold; text-align:center"> Prosimy o poswiecenie czasu i poznanie nas!</p>
</br>
<tr>
<td align="center"><input type="submit" value=" Wejscie "></td>
</tr>
</div>
</form>
</body>
</html>
File got extention *.php. It has to load some pics(opona1.jpg...) from $obrazki and if button "Wejscie" is pressed, programm in file glowna.php is called. Two problems:
1. If i try to change top of the program in such way
<html>
<?php
$obrazki = array('opona1.jpg', 'olej1.jpg', 'swieca_zaplonowa1.jpg',
'drzwi1.jpg', 'kierownica1.jpg',
'termostat1.jpg', 'wycieraczka1.jpg',
'uszczelka1.jpg', 'hamulec1.jpg');
shuffle($obrazki);
?>
and to change extetion of head file from *.php to *.html - program doesn't work properly and doesn't show images at all?
2.All image files from $obrazki were of different images and had different names without 1s( like opona.jpg, olej.jpg, swieca_zaplonowa.jpg etc.)from the very begining. But if I tried to insert different images in my program and give them the same names (opona.jpg, olej.jpg, swieca_zaplonowa.jpg...) program started to show old(previous) pix even if i erased them totally. But when i changed names of all images from $obrazki adding 1s to names(like u see now) program started to show these new images.Why have I to do like that? Is this means html save information about image files somewhere? Thnx
First, always try to use English words (like variables or files) in your code. It's easier to understand for readers which don't know your language.
You can't change file extension from PHP to HTML. Only PHP files can execute PHP scripts. (Of course, you can configure your server to execute HTML file as PHP or add rule to htacess to swap extension from .php to .html)
I think it's cache. You should always refresh page few times or use any method to clean cache after making changes (In chrome you can disable cache on the selected page)

Fill HTML table with PHP

I'm going nuts over this table.
In this page I'm supposed to show all the orders made by an user and the code is basically the same I used in another page, but the the PHP code won't freaking fill the HTML table.
<html>
<body>
<h1>Your orders</h1>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Videogame</td>
<td>Price</td>
<td>Payment</td>
<td>Date</td>
<td>Delete order</td>
<td>Game received</td>
</tr>
<?php
$conn=pg_connect('dbname=project user=project password=project');
$user=$_SESSION['Userdata']['username'];
$query="SELECT o.IDOrder, v.Title, o.price, o.paymenttype, o.date FROM negozio_vg.order o INNER JOIN negozio_vg.videogame v ON o.videogame=vIDVideogame WHERE username='$user' ORDER BY o.date";
$result=pg_query($conn,$query);
while ($rows=pg_fetch_assoc($result)) {
printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td><a href='orderhandler.php'>Delete</a></td><td><a href='orderhandler.php'>Confirm</a></td></tr>", $rows['title'], $rows['price'],$rows['paymenttype'],$rows['date']);
}
?>
</table>
<form action="homeUser.php">
<input type="submit" value="Ritorna al menu">
</form>
</body>
</html>
I'm seriously going nuts, because, as I said, I used the same code in another page.
Even worse, the query actually works, and so does the while loop (I tried using an echo instead of a printf and it printed the whole order list)
Any suggestions?
You have 5 placeholders and provide only 4 values. It's possible the error is either suppressed or it's not displaying in the HTML. Regardless, either remove an %s or add another substitution value $rows['some_column_name']

Reusing php prepared statement will only return last entry of mysql table

I'm encountering a strange problem. To be honest this is the first time I try to re-use a prepared statement on the same php page. In this case I really need it to work since the solution of doing 2 identical statements with different variable names seems redundant. Anyway Here's what I did.
$mysqli = new MySQLi(HOST,USER,PASSWORD,DATABASE);
$image_from_database = $mysqli->prepare("SELECT slider_id, slider.images_id, images.images_id, images.image_name,
images.image_path, images.image_type, images.image_size,
image_tag_name, image_tags.date FROM slider
LEFT JOIN images ON slider.images_id = images.images_id
LEFT JOIN image_tags ON image_tags.images_id = images.images_id");
$image_from_database->bind_result($sliderID,$sliderImageID,$imageID,$imageName,$imagePath,$imageType,$imageSize,$tagName,$tagDate);
$image_from_database->execute();
$image-from_database->store_result();
Then for the call:
<div class="large-6 columns">
<fieldset class="slider_control">
<legend>Images From Database</legend>
<div class="slider_image_edit">
<div class="slider">
<?php
while($image_from_database->fetch()){
if(!empty($sliderID)){
echo'
<div><img src="../'.$imagePath.'"></div>';
}
}
$image_from_database->free_result();
?>
</div>
Then later on the page I want to display the results in a table instead of an image slider...
<fieldset>
<legend>Choose the different Images to edit, you can view the slider to see the order they are in</legend>
<form action="" method="post" enctype="multipart/form-data">
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Tag</th>
<th>Type</th>
<th>Size</th>
<th>Edit</th>
<th>Delete</th>
</thead>
<tbody>
<?php
$image_from_database->execute();
while($image_from_database->fetch()){
echo '
<tr>
<td>"'.$sliderID.'"</td>
<td>"'.$imageName.'" </td>
<td>"'.$tagName.'" </td>
<td>"'.$imageType.'" </td>
<td>"'.$imageSize.'" </td>
<td>Edit</td>
<td>Delete</td></tr>';
}
?>
</tbody>
</table>
</form>
</fieldset>
When I load the page, the slider will display perfectly with all the corresponding images, but on the list it will only display the last row of the table in this particular example it will display something like:
ID Name Tag Type Size Edit Delete
"2" "bf535be38b469cfbcf6db6d02ba3a9d0.jpg" "Colleges & Programs" "image/jpeg" "82993" Edit Delete
"2" "bf535be38b469cfbcf6db6d02ba3a9d0.jpg" "Colleges & Programs" "image/jpeg" "82993" Edit Delete
The edit and delete dont do anything at this time, they are just there as placeholders for what I want later on.
Anyway, can someone tell me why the query will work on the first part of the page but not on the second one?
This is because you already showed all records and the array you got from the database is already at it's end. So when you call it again, it will start with the last.
Do what Jeroen told you, store the result in an variable or something and then reset it.

Trouble querying Mysql database from web

I am having trouble setting up a query, it seems very simple but I cannot seem to determine if my database logic is incorrect or whether the query is incorrect.
There is one database with 3 tables, clients, orders and package.
The clients table has 3 fields, ID{primary key auto increment), email (varchar) and organisation (varchar).
The orders table has 10 fields, ID(from above), OderID (PRimary, autoincrement), WorkID (from package table), and othr fields relating to file paths, comments, feedback and date.
The package table has 2 fields, WorkID (primary Key autoincrem), name(varchar)
This is what I want the query to do:
The query must get all the rows from orders table where WorkID= 1 and must get the organisation field from clients based on each order. I am then going to order the rows by date.
Am I meant to be suing a join to get this query to work or is there a flaw in the database logic? Now yes I already know there is an error below as i am not comparing an ID from the two tables, but what I want to happen is for it to first get all the rows from orders where WorkID = 1 then add the clients.organisation field to each row found from WorkId = 1 where ID from clients corresponds to the ID assigned to that row.
Thanks for any help
$query = "SELECT *
FROM orders INNER JOIN clients ON orders.ID = clients.ID
WHERE WorkID = 1
ORDER BY Date DESC";
WORKING NOW__________________________------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>
Ok guys ive got the query working but for some odd reason the number of rows being echoed in while loop i have set up is always 1 less than num_rows. Anyone have any idea as to why? This is my echo
<?php
include "../includes/connect.php";
$query = "SELECT *
FROM orders INNER JOIN clients ON orders.ID = clients.ID
WHERE WorkID = 1
ORDER BY Date DESC";
$result = mysqli_query( $link , $query );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta name="google-site-verification" content="qH5HloAtcJbjEVuEx3vDy_Rmj7Zjw8Mtsuuqdrd1c3Y" />
<link href="../styles/dark-main.css" rel="stylesheet" type="text/css" />
<link href="../styles/nivo-slider.css" rel="stylesheet" type="text/css" media="screen" />
<link href="../styles/jquery.galleryview-3.0.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="../scripts/jquery.nivo.slider.pack.js"></script>
<script type="text/javascript" src="../scripts/page-scripts.js"></script>
<script type="text/javascript" src="../scripts/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="../scripts/jquery.galleryview-3.0.js"></script>
<script type="text/javascript" src="../scripts/jquery.timers-1.2.js"></script>
<script type="text/javascript" src="../scripts/validator.js"></script>
</head>
<body class="portfolio">
<!--TOPBAR STARTS HERE-->
<?php include"../includes/topbar.php"; ?>
<!--TOPBAR ENDS HERE-->
<!--HEADER STARTS HERE-->
<?php include"../includes/header.php"; ?>
<!--HEADER ENDS HERE-->
<!--SLIDER STARTS HERE-->
<?php include"../includes/slider.php"; ?>
<!--SLIDER ENDS HERE-->
<!--MIANCONTENT STARTS HERE-->
<div class="contentcontainer">
<div class="contentcontainercenter">
<div class="portfoliowrapper">
<h2>Portfolio</h2>
<div class="box">
<div id="conversionworks" class="conversionwork">
<h3>Heading</h3>
<span class="message"> message </span>
<div class="blockwrapper">
<?php
while( $row = mysqli_fetch_array( $result ) ){
echo '
<div class="itembox">
<div class="imagewrapper">
<a class="thumbnail" href=""><img src='. $row['ThumbPath'].' /><span><img src='. $row['FilePath'].' /></span></a>
</div>
<div class="detailsbox">
Company:<span class="details"> '.$row['Organisation'].' </span><br />
Theme:<span class="details"> '.$row['Theme'].' </span><br />
Uses:<span class="details"> '.$row['Tech Used'].' </span>
</div>
</div>'
;}
?>
Also i have a question i regards to safety of a database. I have file paths stored in the database which get echoed according to each record fetch no user interaction all done via the server on page load, is it insecure to do so?
2nd question i have mutiple queries on the 1 page, what would be the best way to include each query where it is required? (Would putting it in a separate file and calling it before the echo be best?)
You probably need something like that:
SELECT *
FROM orders o
INNER JOIN clients c ON (c.id = o.id)
WHERE o.WorkID = 1
ORDER BY `Date` DESC
Some side notices : you should change your column naming convention to something more descriptive (I'm talking about orders.id which is in your case is a reference to clients.id). Personally, I prefer to use id as a primary key in each table. Some people like to name it as [TABLE_NAME]_id, in your case order_id, client_id. Secondly, don't use *; list all required fields. Also, I'd recommend to use a newer sql syntax for joining table (use JOIN keyword instead of listing all tables in FROM clause).
Yes using a join would be what you want to do (a left join actually). You can read about them here, or put your tables into a readable state; and I can give you an example.

Categories