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 8 years ago.
Improve this question
I'm trying to fill 3 different tables in my database.
Sale table which has the following rows:
sale_id
fk_sale_user
fk_payment_id
sale_date
Print_for_sale which has:
print_for_sale_id
fk_sale_id
price_print_for_sale
Print_has_size_has_print_for_sale
print_has_size_has_print_for_sale_id
fk_print_has_size_id
fk_print_for_sale_id
Here is a screenshot of my database in mysql workbench so you can situate.
I'm trying to make the "buying" action.
This is my markup and php code:
printdetail.php
<?php
$id= $_GET['print_id'];
$printdetails = getprintdetailsById($con, $id);
$line = mysql_fetch_assoc($printdetails);
$selectsize =" select * from size";
$result=mysql_query($selectsize);
?>
<div>
<img width="800px;"src="<?php echo $line['print_img']?>"/>
</div>
<div>
<span> <?php echo $line['print_title']?> </span>
<form action="addprints.php" method="post">
<ul>
<?php while ($line = mysql_fetch_assoc($result)) { ?>
<li> <input type="checkbox" name="sizes[]" value="<?php echo $line['size_id']?>">
<?php echo $line['size_name']." Price: ".$line['size_price']."€ "?>
</li>
<?php } ?>
<input type="submit" value="Add to Cart" >
</ul>
<input type="hidden" name="print_id" value="<?php echo $id; ?>" />
</form>
</div>
addprints.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 2)";
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectsize = "select *
from size";
$resultsize = mysql_query($selectsize);
while($linesize = mysql_fetch_assoc($resultsize))
{ $size_price = $linesize["size_price"]; }
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{ $sale_id = $linesale["sale_id"]; }
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
$selectprinthassize = "select *
from print_has_size";
$resultprinthassize = mysql_query($selectprinthassize);
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{ $print_has_size_id = $lineprinthassize["print_has_size_id"]; }
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{ $print_for_sale_id = $lineprintforsale["print_for_sale_id"]; }
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
?>
I am very new to php and mysql so I'm sorry if this is a dumb or bad question. I can't figure out what I'm doing wrong...
The table Sale is being updated correctly in phpmyadmin. Everything is working. User ID is OK and payment ID is OK too. (I haven't done the payments part yet so I just used a number to test.)
The table Print_for_sale is updating the correct sale ID (fk_sale_id), however the price_print_for_sale is always the same, no matter what print I choose. It's always 150 when sometimes it should be 65 ou 25.
(The print price is defined in the size table. So far I have 3 different sizes, so different prices.)
The table Print_has_size_has_print_for_sale is updating the correct print_for_sale ID, but the fk_print_has_size_id is always number 12 (which is the last from that list) and it has nothing to do with my choices on the form. I believe this is what is making the price come out wrong. If it's always the same combination of prints and size (print_has_size), then it's always going to have the same price... Why is this happening?
Can someone please help me?
Here are some screenshots of phpmyadmin:
Edit: This is the function I used:
<?php
function getprintdetailsById($con, $print_id){
$question = "select * from print where print_id=".$print_id;
$result = mysql_query($question, $con);
return $result;
}
?>
This is a lot of info.. I guess we can start debugging. Let's begin with your while loops. Inside your for loop, the first line select * from size, this should return an array, then you are iterating this array with your while loop, but you are assigning them to just one variable. This will overwrite the data result of the last iteration. Is this what you want?... to be continued.
You don't want that to be overwritten.. so what you need to do for that while loop is assign it to an array, like this:
while ($linesize = mysql_fetch_assoc($resultsize)) {
$size_price[] = $linesize["size_price"];
}
so, once you have the $size_price[] with all the desired sizes, we move on.. your code now runs select * from sale where you want all the sale_ids from. So just like above, assign it to an array, we'll say $sale_ids[]
Now you are trying to run a query that inserts data to the print_for_sale table, but the data comes from the two different arrays you created above.. this is will not work, and if so, you would need to come up with crazy loops and iteration like you already have tried.
To fix it, you first need to look at your tables, assign them unique ids, and link them through indexes, once you do that, you need to use the JOIN SQL command on your queries to get the matched data together.
I would look into separating your code as well. this will help you reuse it. You should look into an MVC framework. Ever heard of Codeigniter? its very easy to learn and powerful for applications.
Hope this helps.
Your code could use work, but I think that your problem is a misplaced bracket at the end. It should be:
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{
$print_has_size_id = $lineprinthassize["print_has_size_id"];
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{
$print_for_sale_id = $lineprintforsale["print_for_sale_id"];
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
}
The replace code should be in the loop. In your original code, you looped through all the values, ending with the last one, and then used it.
Related
I have these codes. I chose the do-while loop, so I can do the looping, but somehow it doesn't work.
So, in my database, there are at least 5 rows from the "SOALTXT" field, that have id=S01, which mean, tht it should do looping for 5 times. But somehow it only shows one row.
Like this:
not expected output:
<?php
include "koneksi.php";
$query = mysqli_query($connection,"SELECT * FROM buatsoal_db ORDER BY ID DESC");
$result = mysqli_fetch_array($query);
$id = $result['ID'];
?>
<?php
do{ ?>
<form method= 'post'>
<input name='next' type='submit' id='next' value='next'>
</form>
<?php if(isset($_POST['next'])){
> $row = mysqli_fetch_array ($query);
echo $row['SOALTXT'];
?>
<br>
<br>
<?php
}
?>
<?php }
while ($id =='S01');
?>
For the output, I expect 5 'next ' button, and when it clicked, show up each one 'soaltxt'.
The variable $id is not being updated inside the do while loop. Just add another
$id = $row['ID']
before the echo in the loop.
Edit:
I was going to post a new snippet but the answer from #Omar Abbas is along the lines of what I intended. I would get the form outside of the loop and add a hidden input to pass an index to the next page so you know how many times you pressed next so you know how many rows to display.
Learning to ask the right questions is important in this industry. Important parts of it are good phrasing and as few assumptions as possible.
Answer to your question you are using mysqli_fetch_array() find details about mysqli_fetch_array now you also need to check on which index your id resides in the $row like $row[0] or whatever that index might be, and assign this value to the $id variable like $id = $row[0] and then put that into while($id = 'S01')
possible solution, only fetch the records that have id = S01, use mysqli_fetch_assoc() and use While loop, find details mysqli_fetch_assoc.
$query = mysqli_query($connection,"SELECT * FROM buatsoal_db WHERE ID=S01");
$result = mysqli_fetch_array($query);
while ($row=mysqli_fetch_assoc($result)){
echo $row['ID'];
}
I'm working on a forum page. Right now what is happening, when a user submits a reply to a topic: that reply gets submitted to all the comments. I need to check to see where the array value is, compared to the topic. Like for example topic 3, and the user replies: it only replies to that topic, no others.
<form enctype="metadata/form-data" method="post">
<?php
$reply = $_POST["reply"];
$submit = $_POST["submit"];
$uID = $newRow["ID"];
$cID = $comment["comment_ID"];
$ucID = $comment["ID"];
//this is where I've been stuck.
if(isset($submit)){
foreach($reply as $myReply){
echo $myReply.'<br />';
}
}
else{
echo "No result here.";
}
?>
<div class="textInput">
<textarea name="reply[]" maxlength="255"></textarea>
</div>
<div class="submitInput">
<input type="submit" name="submit" value="reply" />
</div>
</form>
I don't have a clear image of what it is you are using exactly, but I'll make up an example which I'm sure will be of help. I'm going to assume you're using MYSQLI
Steps:
Step 1 ) Store your original post in a table (Original post will be OP from now on)
Step 2 ) Create a table for the replies to go in
Step 3 ) Create a relationship (foreign key)
Step 4 ) Get the original posts you want to be visible (or is it only one?)
Step 5 ) Get related replies
Step 6 ) Put related replies as a sub-array within the OP array.
Example:
First, get the OP. STEP 4
<?php
//In case of multiple:
$getOP = "SELECT * FROM original_posts WHERE ID IN(1,2,3)";
//In case of single:
$getOP = "SELECT * FROM original_posts WHERE ID = 1";
?>
Now, get those ID's in PHP.
<?php
//in case of multiple:
$IDArray = array();
$getOPResult= mysqli_query($con, $getOP);
foreach($getOPResult as $row){
$IDArray[] = $row['ID'];
}
//In case of single, no need for a loop
$result = $getOPResult->fetch_object();
$OPID = $result->ID;
?>
Now, follow up with the replies STEP 5
<?php
//In case of multiple
$getReplies = "SELECT * FROM table_replies WHERE OPID IN(".implode(',', $IDArray).")";
//In case of single
$getReplies = "SELECT * FROM table_replies WHERE OPID = $OPID;
?>
Now, we'll fuse the arrays. This step isn't even necessary with a single OP:
<?php
$myReplies = mysqli_query($con, $query);
$fusedArray = array();
foreach($myReplies as $row){
//put the replies into an array with the OP's ID as a key
$fusedArray[$row['OPID']] = $row;
}
?>
Last step - Rendering it all:
<?php
$html = '';
foreach($getOPresult as $OP){
//set replies array
$thisOPID = $OP['ID'];
$relatedReplies = $fusedArray[$thisOPID];
//From this point on, you can easily loop over the replies for every OP
$html .= '<div class="myPost">';
$html .= 'I'm going to output OP data here';
$html .= '<div class="myReplies">';
//Start looping over the replies and outputting it here
foreach($relatedReplies as $reply){
$html .= 'I'm rendering reply data here';
}
$html .= '</div>';
$html .= '</div>';
}
echo $html;
?>
To close
Now, this isn't extremely specific since I don't have much information, but the logic is there and this logic should suffice in most cases.
Before starting a discussion, please remember that this is just an example of structure and logics.
However you want to output your HTML is on you and so is the coding style. Whether you want to use procedural mysqli or not or how you secure it against MYSQL injection and such, are not related to this question and thus should not be discussed. I'm only trying to help OP with the logistics of it all.
Have a nice day, and I hope this helps :)
EDIT:
I'm sorry, you seem to have changed your question.
In this case, I would simply recommend you to use a hidden field in the form such as this:
<input type="hidden" name="OPID" value="$IDoftheOP"/>
Now, whenever load a topic, just fill the value of the hidden input with the ID of it. When reading out the formdata in PHP, simply read it out and that's the ID you need to couple it with.
I'm having some trouble with my php / mysqli code, hopefully you can help me.
I'm currently working on an online shop for a school project. Customers are able to buy things, they get an order number and I'm writing their user_id, the order number, the different products and some other things in a relation.
now the administrator should be able to see all orders.
right now it looks like this (I copied my table into a word table, so it's easier to see the structure):
part of the table
So the problem is that I have two different order numbers (80425 and 14808) and I want to show each number (and the name and adress of the custumer, too) only one time, but for each order number all different ordered products.
I imagine it like this:
part of the table (more organised)
(it's german, I hope you still get what I mean)
So this is the code right now for getting all the information and show them in a table:
$selection = "SELECT * FROM kundenbestellungen, zahlart, produkte, user, status_bestellung, wohnsitz, kontodaten
WHERE b_zahlung_id = z_id
AND b_produkte_id = p_id
AND b_user_id = u_id
AND b_status_id = sb_id
AND w_user_id = u_id
AND d_user_id = u_id";
$sql = mysqli_query ($dblink, $selection) OR die (mysqli_error($dblink));
if (mysqli_num_rows ($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
?>
<tr>
<td>
<?php /*Change the status to sent*/
if ($row['b_status_id'] == '0') {
echo $row['sb_status'];
?>
<form action="admin-bestellungen.php" method="POST">
<input type="hidden" name="id" value="<?php echo $row['b_id']?>">
<input type="submit" name="versenden" value="versenden">
</form>
<?php
} else {
echo $row['sb_status'];
}
?>
</td>
<td> <?php echo $row['b_nummer'];?></td>
<td><?php echo $row['u_vorname']." ".$row['u_nachname'];?></td>
<td><?php echo $row['p_produktname'];?></td>
<td><?php echo $row['b_menge_produkt'];?></td>
<td><?php echo $row['b_einzelpreis'];?></td>
<td><?php echo $row['z_art'];?></td>
<td><?php echo $row['b_zeitpunkt'];?></td>
</tr>
<?php
}
}
I'm really confused. I tried this below the $selection part, just to start with something:
$anzahl_bestellungen = "SELECT COUNT(DISTINCT b_nummer) AS nr FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['nr']);
and the code counts the amount of the different order numbers (8). But if I use it without COUNT, it shows only the first order number (80425) and also counts only 1 result and doesn't get the other 7 numbers.
$anzahl_bestellungen = "SELECT DISTINCT b_nummer FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['b_nummer']);
$b = count($bestell['b_nummer']);
echo "<br>".$b;
I also tried to work something out with GROUP, but then the code shows only one item for each order number.
I tried to work with a for-loop as well, but that didn't work out either.
I thought about a multidimensional array, but I wasn't able to think through that whole thing, I'm not very good at php / mysqli.
So I have no idea how to go on. Maybe you can help me. This is my first question, so please let me know if I need to be more specific or you need more code or anything.
thanks a lot!
I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].
Sorry if this has been asked and answered but I have looked and can't see it anywhere. Yes I am a nooby.
I have a DB with 3 tables: flour, filler and others.
What I would like to do is have a dropdown List. So, if user chooses flour from the Drop Down box it will display flour table. If the user chooses filler then filler table be displayed.
Hope this is clear. I hope you can help. Thanks in advance.
<Form id="form1" name="form1" method="get" >
Supplies of
<select name=filler action="flour.php">
<option value="1" selected>flour</option>
<option value="2">filler</option>
<option value="3">others</option>
</select>
<input type="submit" value="Submit" />
</form>
<?php
header("Content-Type: text/html; charset=windows-1251");
#mysql_connect('localhost','root','');
#mysql_select_db('krendel');
#mysql_query('SET NAMES cp1251');
$res = mysql_query("SELECT * FROM `flour` ") or die(mysql_error());
$res2 = mysql_query("SELECT * FROM `filler` ") or die(mysql_error());
$res3 = mysql_query("SELECT * FROM `addit` ") or die(mysql_error());
Add the action to the form, not select element. So you'd have
<form method="get" action="flour.php">
and
In your form processing script (flour.php), you could so something like this:
switch($_GET['filler'])
{
case '1':
$table = 'flour';
break;
case '2':
$table = 'filler';
break;
case '3':
default:
$table = 'addit';
}
$res = mysql_query("SELECT * FROM {$table}");
If all tables have the same structure, consider combining the tables, and adding a type column (varchar containing either flour, filler, or addit for simplicity).
you could then write the query like this (still using the $table variable name to work with the code above.
$res = mysql_query("SELECT * FROM table WHERE type='{$table}'");
Using mysql_query, and concatenating variables into the SQL is not good practice now - have a look at PDO and parameterised queries as you learn more.
Some quick and dirty display code:
<?php
$results = array();
while($row = mysql_fetch_array($res, MYSQL_ASSOC)) { ?>
$results[] = $row;
}
?>
<table>
<?php foreach($results as $result) { ?>
<td><?php echo $result['column_name'] ?></td>
<?php } ?>
</table>
This should get you started - as I said above, it's quick and dirty. You'll be able to improve upon this as you get more knowledge (properly separating out the HTML from PHP, for example - it's really worthwhile reading up on MVC amongst other patterns).
Just don't use this code on a production system!
Hope this helps.
The page that is going to display the table needs to check the $_GET['filler'] and see what the value is. Since you are using $_GET and a drop box, you should have a white list something like: $filler_white_list = array('flower', 'filler', 'other');
Check to see if the value of $_GET['filler'] is in the $filler_white_list array. If the $_GET['filler'] value is valid, then make your query:
$res = mysqli_query('SELECT * FROM '.$_GET['filler'].';') or die(mysqli_error());
Then loop through the result set to print out to the page:
while($row = mysqli_fetch_array($res)){
//get the columns by using $row['column_name']
//decide how you want to format
}
Things to note: I used mysqli instead of mysql, because the mysql is deprecated (no longer supported), The SELECT statement uses an *, but it is better to list out the names of the column since it is faster. It is not a good idea to use the the values of the drop box as the name of you tables in the database. The less information you reveal about your database, the better. Of course, if this is not for a production DB, then it doesn't matter. But, I think it is always best to think about security even when you're just practicing. Also, I put the $_GET['filler'] in the middle of the SELECT statement because the table's names are the same as the drop box.