So first off, I know this isn't the best method to try and randomize Mysql Rows, but it works for now.
My only issue is that it displays like this:
{"0":"random1","quote":"random1"}
when I want it to display like this
random1
My Code:
`
<?php
$quotes = $DBcon->query(
'SELECT quote FROM quotes ORDER BY RAND() LIMIT 1;');
$result = $quotes->fetch_array();
?> <strong>Daily Quote</strong> - <?php echo json_encode($result); ?>
<input type="submit" class="btn btn-primary" value="Get Quote" />
</div>`
*No that is not my only PHP code, but that's the only section for this issue. Also, if I did something wrong, please correct me as I'm still learning.
*
change the fetch array return two array one with numeric index and other with string index so use fetch_assoc()
$result = $quotes->fetch_array();
to
$result = $quotes->fetch_assoc();
to display result
$result['quote']
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'];
}
The below code is returning rows of checkboxes (the right number per the mySQL table) and with no error. The problem is that it is not grabbing the column values ((as per: ".$row['Zone'].": ".$row['RowNumber']. ))to place beside said checkboxes.
<?php
include'connect.php'
?>
<form method="post" action="chooseDate.php">
<?php
$sql = "
SELECT s.RowNumber, s.Zone,
FROM Seat AS s
LEFT JOIN Booking AS b, ON s.RowNumber = b.RowNumber,
AND b.PerfDate = ?,
AND b.PerfTime = ?,
WHERE b.RowNumber IS NULL,
GROUP BY s.RowNumber
";
$date = "$_POST[Date]";
$time = "$_POST[Time]";
$handle = $conn->prepare($sql);
$handle->execute(array($date, $time));
$res = $handle->fetchAll();
foreach($res as $row) {
echo "<input name='Seat' type='checkbox' value='".$row['Zone'].":
".$row['RowNumber']."'><br>";
}
?>
<input class="mybutton" type="submit" value="Choose Seat"/>
</form>
I have run queries using identical methods and they display the results as expected. The only difference here is that the query is LEFT JOIN. The results display in shell. This is a sample of the results and the expected output of one checkbox.
|**RowNumber**|**Zone**|
|-------------|--------|
|Z20 |box 4 |
Where am I going wrong? Thanks in advance.
Have you looked at the HTML output? You put the text inside the input element. The closing > is after the text.
You could fix that simply by just moving the > to the front, but I think it's bettter to generate a <label> element after the checkbox or surrounding the checkbox. If you give the checkbox an id, and the label a for attribute pointing to that id, the text is clickable too, which make an awesome UX. :)
So I suggest changing the for loop like this:
$idcounter = 0;
foreach($res as $row) {
$id = 'Seat' . ($idcounter++);
echo "<input name='Seat' type='checkbox' id='$id'><label for='$id'>".$row['Zone'].":".$row['RowNumber']."</label><br>";
}
Note that I removed the value attribute. I'm not sure if you would need it, but maybe you need both: the value and the label. If so you can put back that attribute like you had before, as long as you make sure to close the input element before opening the label.
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.
I have written an sqlite full text search which i am doing something wrong. If i type in my search "Puma Adidas" i want to search both words in the column MAKE.
At the moment it will only display one word if it exactly matches the search word. I just cannot figure out what i have missed, could i have some assistance please?
Thanks
HTML:
<form action="search.php" method="get">
Search: <input type="text" name="SEARCH">
<input type="submit" class="btn btn-default">
</form>
PHP:
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE IN('$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
I did change the PHP code to this:
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE ('%$search_string%') AND VISIBLE='YES' ORDER BY DATE DESC");
But it still does not work unfortunately, same issue.
Try using LIKE, not IN. IN is used for a different purpose.
$search_string = $_GET['SEARCH'];
$result = $db->query("SELECT * FROM PRODUCTS WHERE MAKE LIKE '$search_string') AND VISIBLE='YES' ORDER BY DATE DESC");
Check the syntax for the LIKE statement; you'll need to surround your search string with percent signs if you want to search the entire field for the search term.
Is there anything wrong in this scenario? the result isn't showing. maybe i'm getting the syntax wrong?
// fetch the latest tweet
$lastTweet = '';
$q2 = "SELECT tweet FROM timel ORDER BY id DESC LIMIT 1";
list($lastTweet) = $conn->get_results($q2);
if(!$lastTweet){
$lastTweet = "You don't have any tweets yet!";
}
var_dump($lastTweet);
and this on the html body:
<span class="latest"><strong>Latest: </strong><span id="lastTweet"><?.=$lastTweet?></span></span>
If you changed your first line to
$lastTweet = array();
And your third line to
$lastTweet = $conn->get_results($q2);
Then you would be able to use
<?php var_dump($lastTweet); ?>
But in your case lastTweet contains a string of text, hence you need to use echo to print it's content.
<?php echo $lastTweet ?>
Nb: i'm not sure about your project details but i'm guessing you'd need to also get the date, maybe id and user_id of the tweet, if that's the case, you might want to make lastTweet an empty array()
Use this:
<span class="latest"><strong>Latest: </strong><span id="lastTweet">
<?php echo $lastTweet; ?></span> </span>
Saludos ;)