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']
Related
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
  |
RICERCA PER PAZIENTE
  |
RICERCA PER GENE
  |
RICERCA PER VARIANTE
  |
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.
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.
You can see that I have a 3 element array. I am using a while loop to then print out all 3 values into a table, one row for each of the three values, but I do not understand how three rows are being printed out when I only have one row hard coded using html code. The PHP while loop does not echo the tr and td tags for each row because those row and detail tags are outside the PHP code. The code works -- it prints out one additional new table row for each value of "mary","donna","shirley", but I do not understand how. I could see it working if the tr and td tags were output by a PHP echo statement inside the while loop, but that is not the case here.
<html>
<body>
<table cellspacing ="2" cellpadding ="2" align ="center" border="8">
<?php
$ar1=["mary","donna","shirley"];
$len=count($ar1);
$ct=0;
?>
<?php while ( $ct<$len) { ?>
<tr>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
</tr>
<?php } //end while loop?>
</table>
</body>
</html>
I believe the answer lies in the fact that HTML is an interpreted language not a compiled language.
So in this case your php while loop is setting the browser back to the spot just before your first tr tag so it goes through and interprets those tags again, and as it does this it puts them to the page again. Doing your while loop like this is a cheap way to do echos essentially.
I'm not a PHP master by any means, but from my understanding of how HTML is read and how PHP works this is my answer.
Your <tr> tag is inside the while loop. If you want just one row, try this-
<html>
<body>
<table cellspacing ="2" cellpadding ="2" align ="center" border="8">
<?php
$ar1=["mary","donna","shirley"];
$len=count($ar1);
$ct=0;
?>
<tr>
<?php while ( $ct<$len) { ?>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
<?php } //end while loop?>
</tr>
</table>
</body>
</html>
This piece of code:
<?php while ( $ct<$len) { ?>
<tr>
<td>
<?php echo $ar1[$ct];
$ct++;
?>
</td>
</tr>
<?php } //end while loop?>
is the same as
<?php while ( $ct<$len) {
echo "<tr>
<td>";
echo $ar1[$ct];
$ct++;
echo "</td>
</tr>";
} //end while loop?>
if you analyze code more deeply..u will understand it yourself..you said "The php while loop does not echo the tr and td tags for each row because those row and detail tags are outside the php code"
but it does ..the html code is not the part of php code it coded outside php scope...and whenever your while loop executes it again reads the tr and tg tag and insert row and hence u get three rows printed ...
It's an easy case of PHP basic capabilities.
See http://php.net/manual/en/language.basic-syntax.phpmode.php
Everything outside of a pair of opening and closing tags is ignored by the PHP parser which allows PHP files to have mixed content.
PHP parser, don't need to know what is inside the While Loop, it just repeat to the output.
In a php file, by escaping the php code (by way of ?> you basicly say to the script, now comes something non php, you provide Html tags which are then interpreted by the browser as html code. But because you're still in the loop (you haven't ended it by adding an closing tag } you repeat the exit from the code, presenting html, and then entering the code again.
Some coders prefer to just exit php code and to show some html code with a few php tags here and there when there's a large amount of html being displayed. It's a lot less typing than continually using echo statements.
So I was just wondering if it was considered bad practice to open and close PHP statements, and let me explain what I mean. I know I can make variables at the beginning of my code but I like to group stuff together.I'm not sure if making one big PHP statement with all my variables is better / worse / same as opening and closing PHP statements similar to the example below.
<html>
<head></head> <---- HTML STUFF
<?php
(php stuff where connection to mysql db goes and other variables and errors)
?>
<body>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
<html> <----- HTML stuff
<?php
(php stuff to call a specific table from DB)
?>
</body>
<html>
BTW the php variables I'm talking about are specific select statement from the DB.
ACTUAL CODE: or should select statements be at beg or sep file?
<table>
<tr>
<td align="left" width="200px">
Cover: Original Total
</td>
<td width="200px" align="center">
<?php
$original = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"original\"";
$orig_con = mysqli_query($comic_connect, $original);
$orig_total = mysqli_num_rows($orig_con);
echo $orig_total;
?>
</td>
</tr>
<tr>
<td width="200px" align="left">
Cover: Variants Total
</td>
<td width="200px" align="center">
<?php
$variants = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"variant\"";
$variant_con = mysqli_query($comic_connect, $variants);
$variant_total = mysqli_num_rows($variant_con);
echo $variant_total;
?>
</td>
</tr>
<tr>
<td align="left" width="200px">
Cover: Baby Totals
</td>
<td width="200px" align="center">
<?php
$baby = "SELECT * FROM `comic_db`.`comic_db` WHERE comic_cover=\"baby\"";
$baby_con = mysqli_query($comic_connect, $baby);
$baby_total = mysqli_num_rows($baby_con);
echo $baby_total;
?>
I'm assuming the repeated <html> tags in your example are just placeholders and would actually be <div>s and other elements making up the actual content of the page.
Your example is what's commonly called "spaghetti code" because it can quickly turn into an unmaintainable mess because you can't clearly see an overview of the HTML, nor can you see all the PHP code in one place.
The main thing to keep in mind is separating application logic (such as your database queries) from presentation (HTML and presentation logic like looping over an array to display it as an HTML list).
At the very least you'd want to put the main PHP code at the top of the file like you said, but it would be much better if it was in a separate file.
P.S. Any beginner book on PHP will discuss this in detail.
I am using this fantastic example of a jQuery editable invoice as a template for creating dynamic invoices for my users.
It's working quite well and I am successfully generating the items but I now need to save the values entered into the various text fields and enter them into the MySQL database.
I am confident in doing the MySQL entering with PHP but what makes this trickier is that the amount of 'invoice items' is completely dynamic and I am unsure how I can get PHP to 'check' through the pages text fields and find new ones, group them and then add them to my DB.
Here is an example of my code that I am using to generate the items:
<?php if($invoice_items->result_array()) { ?>
<?php foreach($invoice_items->result_array() as $invoice_Row): ?>
<tr class="item-row">
<td class="item-name">
<div class="delete-wpr">
<textarea><?php echo $invoice_Row['item_name']; ?> Facility Booking</textarea>
<a class="delete" href="javascript:;" title="Remove row">X</a>
</div>
</td>
<td class="description">
<textarea><?php echo $invoice_Row['description']; ?></textarea>
</td>
<td><textarea class="cost">$<?php echo $invoice_Row['hourly_cost']; ?>.00</textarea></td>
<td><textarea class="qty"><?php echo $total_time_hours; ?></textarea></td>
<td><span class="price">$<?php $unit_total = $invoice_Row['hourly_cost']* $total_time_hours; echo $unit_total;?>.00</span></td>
</tr>
<?php endforeach; ?>
<?php } ?>
I am thinking that I need to perhaps generate unique ID's for each invoice items text field, ie item-1-desc, item-1-cost etc, but that involves writing javascript which I know almost nothing about. Also I would still have to get PHP to loop through the ID's somehow until it reached the end...
If anyone has attempted something similar before or you can see a solution to my problem I would greatly appreciate your help.
Thanks,
Tim
Use the php form array syntax name="item-desc[<?php echo $id?>]"
You can then iterate them on the backend with foreach to store the data. You have the id's as keys to the arrays so it should be fairly trivial to update the db.