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.
Related
I have a problem here with break and loops things in php.I have an input type, if I give the id 2 for ex, if there is 2 in db then only "You liked this url already" should be appear.This works. If I give then id 3 it says "Data added".Good for now.But if I enter again id 3 it says:
Data added!You liked this url already
and a new value of 3 is posting in the db.How to avoid this? Here is my function:
<form method="post">
Url id: <input type="text" name="urlid" id="urlid">
<input type="submit" name="givelikes" value="Give Likes">
<br />
<br />
</form>
<?php
if(isset($_POST['givelikes'])){
$urlid = $_POST['urlid'];
$con = mysqli_connect('localhost','root','root', 'db');
$user = $_SESSION['sess_user'];
$query=mysqli_query($con,"SELECT likes FROM users WHERE user='".$user."'");
$row = mysqli_fetch_array($query);
$array = explode(" ", $row['likes']);
foreach ($array as $value) {
echo $value;
echo $urlid;
if($value == $urlid){
echo "You liked this url already";
break;
}
else{
$array = $row['likes'];
$array .= " ";
$array .= "$urlid";
$query = ("Update users set likes = '".$array."' where user = '".$user."'");
if(mysqli_query($con,$query)){
echo "Data added!";
}
else{
echo "ERROR: Could not able to execute sql: " . mysqli_error($con);
}
}
}
}
?>
Currently you're looping through all "likes" and comparing them. So the sequence of steps is like this:
Enter 2
No likes yet, so the data is added
Enter 2
Loop over likes, find 2, data was already added
Enter 3
Loop over likes, find 2, not match so data is added
Enter 3
Loop over likes, find 2, not match so data is added
Continue looping, find 3, data was already added
Correcting this is going to involve changing your design a bit. Right now you have one de-normalized record with a string of space-delimited "likes". Normalize your data. Have one record per "like". And instead of constantly updating a single record, insert new records.
Then when you want to see if a "like" already exists, you can use a WHERE clause. Something like this:
SELECT * FROM users WHERE user=? AND like=?
(Note: This is using query parameters as a prepared statement. This is highly recommended. Your current code is wide open to SQL injection.)
If any record is found at all, then the item was "already liked" and you can output the message. If no record was found, INSERT a new one for that "like".
No need for a loop.
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'].
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.
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.
I run a script to create an order form, this is just a really small sample. I'm not so good with PHP and dynamic forms. It pulls data from mysql database.
<td>
<h3>Round Cuts</h3>
<?php while($row = mysql_fetch_array($round_cuts)){
$round_box_value = #$row["meat_names"];
$round_box_value_name = #$row["meat_names"];
echo " <input type=\"checkbox\" name=\"round_box_value\" value=\"$round_box_value_name\"> $round_box_value_name";
echo "<br>";
}?>
</td>
I've ever really only built basic contact forms, how could I process a dynamic form like this. If all else fails I would just take all the possible elements and program this like it was a not dynamic. There must be a better way though.
Even a link to a website would be helpful. I've been searching for a solution. Thanks.
I'll assume your table as a primary key of id
Start off with a minor change to your checkboxes:
<?php
while($row = mysql_fetch_array($round_cuts)){
echo sprintf('<label><input type="checkbox" name="round_box_value[]" value="%s"> %s</label><br>', $row['id'], $row['meat_names']);
}
?>
The name now has an [] at the end to tell php it's an array of values + I've wrapped the checkbox in a label for convenience.
Then when you process the form, you can simply iterate through round_box_value like so
<?php
foreach ($_POST['round_box_value'] as $id) {
// $id is the table reference from your previous table
}
// or query all the rows selected
$ids = array_map('intval', $_POST['round_box_value']); // "basic" sql injection handler
$sql = "SELECT * FROM table WHERE id IN (".implode(",", $ids).")";
should produce something like:
SELECT * FROM table WHERE id IN (2,5,7)