Displaying result from mysqli_query - php

I already searched for my answer, but all of the solutions do not fit to my problem. I want to build a forum, where first of, all questions are requested from my MySQL database. Then I want to find out the date of the latest entry for each question, so I created this:
while ($array = mysqli_fetch_assoc($res_page)) {
$get_latest_date = "select * from forum"
. " where id = "
. $array["id"]
. ' order by date DESC'
. ' limit 1';
$latest_date = mysqli_query($con, $get_latest_date);
$date = mysqli_fetch_row($latest_date);
echo '<div class="forum_preview">'
. '<a href=#" class="forum_preview_question">'
. $array["question_short"]
. '</a>'
. '<p class="forum_preview_date">'
. $date["date"]
. '</p>'
. '<p class="forum_preview_comments">'
. $number_of_questions
. '</p>'
. '</div>';
}
My problem is, that showing the latest date is not working, because I cannot get the result out of my mysqli_query.
Can anybody show me where my mistake is or does anybody have another idea?

I think what you are looking for is mysqli_fetch_assoc, mysqli_fetch_row returns an array, mysqli_fetch_assoc returns an associative array so you can get data by keys.
$latest_date = mysqli_query($con, $get_latest_date);
$date = mysqli_fetch_assoc($latest_date);
echo $date["date"];

Related

Inserting wrong data in to the database with $wpdb->insert

So hey guys!
I currently have a code that gets data from a custom table called wp_refundrequests, and prints them as a table to the page. On the page the admin can either Accept, or Deny the request by pressing a button on the side of each order. Denying the request just deletes the request from the table, but accepting should delete it from the current table and insert the information to the next table called "accepted requests".
The wp_refundrequests table contains customer's order that they want to refund.
The code that gets the info and prints it:
global $wpdb;
$requests = $wpdb->get_results("SELECT * FROM wp_refundrequests", ARRAY_A);
foreach ($requests as $row) {
echo "<div class='requests'>" . "<li class='refunds'>" . "Palauttajan nimi: ".
$row['customer_name'] . "</br>" ."Palautettavat tuotteet: ".$row['product_name']."<br> "."Määrä: ".
$row['product_qty'] . " "
. "<br>Kommentti: " . $row['comment'] . "<br> " . "Hinta: " . $row['refund_total'] . "€ " .
"<br>" . "Päivämäärä: " . $row['request_date'] . " " .
"<a class='right' href='admin-page?deleteid=" . $row['request_id'] . "'>Deny</a></li>" .
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']
. "'>Accept</a></li>" . "</div>";
$_SESSION['custname'] = $row['customer_name'];
$_SESSION['prodname'] = $row['product_name'];
}
With my current code, the "Accept" button deletes it, and inserts information in to the new table, BUT the information that is inserted is wrong. It seems like it wants to either insert the latest data that had been inserted in to the wp_refundrequests table to the wp_acceptedrequests, or it keeps the data from the latest refund request and tries to insert that instead because for example as seen here(Sorry for the bits of Finnish as well):
If I were to click the "Accept" button on the above, older one, the query would still insert it like this:
So it basically inserts the info from the latest refund_request insert and inserts that instead of the one selected. However the one that had been selected still gets deleted from the table.
Here's the code that is triggered when the user clicks on "Accept"
$custname = $_SESSION['custname'];
$prodname = $_SESSION['prodname'];
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
/* Query to do whatever here */
$wpdb->print_error();
$wpdb->insert("wp_acceptedrequests", [
"customer_name" => "$custname",
"name_product" => "$prodname",
"date" => date("Y/m/d/G:i:sa") ,
]);
$wpdb->print_error();
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
I have to say I have no idea why it doesn't want to insert the selected request, please comment if there's something confusing, I'll try to clear it up then.
Thanks in advance!
You redefine $_SESSION with in foreach loop so at the end of foreach it will equal to the last one, pass each row parameter to it is accept link like this
"<li class='refundaccepts'><a href='admin-page?acceptid=" . $row['request_id']."&custname=".$row['customer_name']."&prodname=".$row['product_name']."'>Accept</a></li></div>";
Then call it the same way you get $accept-ID
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$custname = $_GET['custname'];
$prodname = $_GET['prodname'];
Note:Iuse my phone so make sure if it was a syntax error in the href part of the code
Please try like this and comment out the session variable.
if(isset($_GET['acceptid'])) {
$accept = $_GET['acceptid'];
$accepted_requests = $wpdb->get_results("SELECT * FROM wp_refundrequests WHERE id = $accept", ARRAY_A);
if( !empty($accepted_requests) ) {
$insert = $wpdb->insert("wp_acceptedrequests", $accepted_requests);
if($insert) {
$wpdb->query("DELETE FROM wp_refundrequests WHERE request_id = $accept");
}
}
}

PHP while loop multiple conditions returning no data?

I have a PHP page that is returning data from a MySQL table. I decided to add a feature that would allow the user to set the number of results they want displayed, in case there are thousands of records for example.
Here is the PHP code that displays the data:
while ($row = mysql_fetch_array($result) && ($row <= $noOfResults)) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
I was hoping that this would only display the data up to the point that the user has selected. So if the user selects 10 results, $noOfResults is set to 10, and it will only fetch the first 10 results from the database. This is currently however only displaying a "-" and the $noOfResults variable (which is desired at this point). Is my syntax wrong or is this not the correct method of going about such a problem?
Thanks, got it working with LIMIT, didn't even think to do that.
Can someone explain why this was downvoted, just trying to learn, so as to write better questions in the future, thanks.
the best way to get limited data from database is LIMIT statement in query .
i assume that your query is
$result= "SELECT * FROM `mytable`";
Just add limit statement in
$result= "SELECT * FROM `mytable` LIMIT '$noOfResults'";
then your while loop will be
while ($row = mysql_fetch_array($result) ) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
You are doing it wrong $row will be an array. So to correct this use mysql_num_rows() function in php to check the number of the rows. Try the code below.
if(mysql_num_rows($result)<=$noOfResults){
while ($row = mysql_fetch_array($result) ) {
echo '<p class="display-date">' . $row['date'] . '</p><p class="display">' . $row['id'] . ' - ' . base64_decode( $row['packetdata']) . '</p>';
echo '<hr align="center" width="100%" />';
echo $noOfResults;
}
}
Hope this helps you

mysqli fetch_object() fatal error

I tried to use mysqli in for my forum database. this is the code I used:
<meta charset="utf-8">
<?php
include("config.php");
$limits = "6";
$forum_id = "2";
$db = new mysqli($INFO['sql_host'], $INFO['sql_user'], $INFO['sql_pass'], $INFO['sql_database']);
$topics = $db->query("
SELECT
`topics`.`start_date`,
`topics`.`title`,
`topics`.`starter_name`,
`topics`.`posts`,
`topics`.`title_seo`,
`topics`.`tid`,
`posts`.`post`
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
`" . $INFO['sql_tbl_prefix'] . "posts` as `post`
WHERE
`topics`.`approved` = 1 AND
`topics`.`forum_id`= " . $forum_id . " AND
`posts`.`topic_id` = `topic`.`tid` AND
`posts`.`new_topic` = 1
ORDER BY
`topics`.`start_date`
DESC LIMIT 5");
echo '<ul id="news">';
while ($topic = $topics->fetch_object()) {
$url = $INFO['board_url'] . '/index.php?/topic/' . $topic->tid . '-' . $topic->title_seo . '/';
$topic->post = strip_tags(str_replace(array('[', ']'), array('<', '>'), $topic->post));
$topic->start_date = date("Y.m.d H:i", $topic->start_date);
echo '
<div class="news">
<div class="newsp"><div class="pteksts">' . $topic->title . '</div></div>
<center><img src="img/news.png"></center>
<div class="teksts" style="padding-bottom: 5px;">' . $topic->post . '</div>
</div>
';
}
echo '</ul>';
?>
and errors i received:
Fatal error: Call to a member function fetch_object() on a non-object in /home/public_html/scripts/news.php on line 35
You give aliases for your tables as topic and post, but then you use the aliases topics and posts. You need to change the table qualifiers to use the same spelling as your table alias.
Wrong, because alias topic is not the same as table qualifier topics:
SELECT
`topics`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
. . .
Right, after changing the table qualifier to match the alias name:
SELECT
`topic`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topic`,
. . .
Right as well, but alias is unnecessary if it's the same as the base table name:
SELECT
`topics`.`start_date`, . . .
FROM
`" . $INFO['sql_tbl_prefix'] . "topics` as `topics`,
. . .
But more to the point, you should always check the return value from $db->query(), because it returns false if there's an error. You can't call any method on a false because that's not an object.
If that happens, report the error but do not try to fetch from the result. It won't work.
$topics = $db->query(...);
if ($topics === false) {
die($db->error);
}
// now we can be sure it's safe to call methods on $topics
while ($topic = $topics->fetch_object()) {
. . .
Re your comment that the output is blank:
I just tested this script and it mostly works, so I can't guess what's going wrong. I suggest you read your http server's error log, which is where many PHP notices and errors are output.
I do see the following notice:
Notice: A non well formed numeric value encountered in /Users/billkarwin/workspace/SQL/22159646.php on line 51
The line is this:
$topic->start_date = date("Y.m.d H:i", $topic->start_date);
The problem is that PHP's date() function takes an integer timestamp, not a date string.
You might want to format the date in SQL, using MySQL DATE_FORMAT() function instead.

full text ranking [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to have ranking based on how many words match user input
How can I have a search engine ranked by amount of words that are typed in and ranked by the amount of types they crop up in the fields title, description, keywords, link.
So the higher results are ordered by having more of the words that the user submitted. Say if the user typed in iPhone, iPhone key word crops up in the link, description and title field, so that would be ranked higher than say Apple which mentions it only in the description and Apple Store which mentions it in the title and the description.
My code is below:
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "Match(title, description, keywords, link) Against ('".implode(' ',$terms)." IN BOOLEAN MODE') ";
}
$secs = microtime();
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
echo '<p class="time">Qlick showed your results in ' . number_format($secs,2) . ' seconds.</p>';
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title1 = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
$title = substr($title1,0,60);
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
While I'm sure it is possible to implement this within mysql, a full-text search index like solr/lucene is designed to handle this stuff directly. You might find better resources & help going down that road.
Using php, copy the array returned by the mysql query:
while ($row = mysql_fetch_assoc($query))
{
$rows[] = $row;
}
Then you can loop over $rows and assign a score to
foreach ($rows as $row)
$row['score'] = score_row($row, $terms)
score_row is a helper method that returns a bigger score depending on which columns have which terms and your definition of "importance".
Then sort thw rows by score, then print the results as you were doing.

Combine Multiple rows from mysql array

right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance
You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...
Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.

Categories