retrieve the last 5 entries in database php pdo - php

$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
$stmt->bindValue(1,$eventwhat);
$stmt->execute();
if ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$_SESSION['id'] = $selected_row['event_id'];
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
$_SESSION['searchresultwhere'] = $selected_row['event_where'];
$_SESSION['searchresultwhen'] = $selected_row['event_when'];
$_SESSION['searchresultwho'] = $selected_row['event_who'];
echo $_SESSION['id']."\r\n";
echo $_SESSION['searchresultwhat']."\r\n";
echo $_SESSION['searchresultwhere']."\r\n";
echo $_SESSION['searchresultwhen']."\r\n";
echo $_SESSION['searchresultwho']."\r\n";
echo "<br/>\n";
}
}
i have the code above to echo the last 5 entries in my database but the problem is it only show 4 it does not get the last 5 so when i have i entry only it does not show anything..what am i missing here why is the last entry not being retrieve?

remove if condition and do like below
$stmt = $dbh->prepare("SELECT * FROM events ORDER by event_id DESC LIMIT 5") ;
$stmt->bindValue(1,$eventwhat);
$stmt->execute();
while($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$_SESSION['id'] = $selected_row['event_id'];
$_SESSION['searchresultwhat'] = $selected_row['event_what'];
$_SESSION['searchresultwhere'] = $selected_row['event_where'];
$_SESSION['searchresultwhen'] = $selected_row['event_when'];
$_SESSION['searchresultwho'] = $selected_row['event_who'];
echo $_SESSION['id']."\r\n";
echo $_SESSION['searchresultwhat']."\r\n";
echo $_SESSION['searchresultwhere']."\r\n";
echo $_SESSION['searchresultwhen']."\r\n";
echo $_SESSION['searchresultwho']."\r\n";
echo "<br/>\n";
}
Your if condition fetaches first row and so while will fetch remaining 4 rows

function makeGetRequest(e, key) {
if (!e) e = window.event;
if (!e.ctrlKey && !e.button == 1) { //this is to be able to open links by clicking the wheel button or ctrl+click
http.open('GET', key, true);
//assign a handler for the response
http.onreadystatechange = processResponse;
//actually send the request to the server
http.send(null);
return false; //this is important, otherwise the href link will trigger and not the onclick
}
}

Related

Creating Like button with jQuery and OOP PHP

I'm trying to create a "Like" button for some articles that I'm printing out from my database. But I'm stuck.
I get to the point where I have posted my vote from the jQuery and I get an empty VAR_DUMP.
And in my OOP class I'm not sure how to print out the votes when I got them to save in the database.
Here's my code
HTML
<?php
// IF theres is a id in adress field
//if(isset($_GET['id'])) {
$page = new CMS();
$gp = $page->getPage();
foreach ($gp as $sp) {
//var_dump($sp);
echo "<div class='pub'>";
echo "<h4 class='pub-headline'>" . $sp['title'] . "</h4>";
echo "<article class='pub_art'>" . $sp['content'] . "</article>";
echo "<p class='pub_created'>" . $sp['created'] . "</p>";
echo "<p class='pub_created_by'>". $sp['writer'] ."</p>";
echo "<button class='show'>Show</button>";
echo "<button class='noshow'>Hide</button>";
echo "<button class='btn-like'>Like</button>"; // Here is my button
echo "</div>";
}
?>
jQuery
/* --------------------Selecting article----------------------*/
// Calling for the method - likes
$(".btn-like").on("click", like);
function like(e) {
e.preventDefault();
// Declaring variables
var id=$(id).val();
var likes=$(".btn-like").val();
console.log('Click Click..');
$.post('classCalling4.php', {
id: id,
likes: likes },
function(data){
console.log(data);
});
}
PHP
var_dump($_POST); // ***** This VAR_DUMP is getting back to me empty
if(isset($_POST['id'])) {
//echo "rätt...";
$id = $_POST['id'];
$likes = $_POST['likes'];
$id = intval($id);
$likes = intval($likes);
$ul = new updateLikes();
if($ul->updateLikes($_POST['id'], $_POST['likes'])) {
echo "Created";
}
else {
} echo "noooo";
}
?>
And finally my OOP class, that is not complete because I'm stuck.
public function updateLikes($id, $likes) {
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
if($stmt->execute()) {
echo "win";
} else {
echo "lost";
}
}
At least your OOP class have some errors:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes+1, WHERE id = $id');
$stmt->bind_param("ii", $likes, $id);
Should be:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + :likes, WHERE id = :id');
$stmt->bind_param(":likes", $likes);
$stmt->bind_param(":id", $id);
or if the meaning is to increase likes only by one, then:
$stmt = $this->db->prepare('UPDATE pages SET likes = likes + 1, WHERE id = :id');
$stmt->bind_param(":id", $id);
If var_dump doesn't return anything, then there might be error in the PHP code (causes error code 500 and depending on PHP settings PHP might return blank page)

PHP MYSQL Get data from database and echo message if no data retrieved

Im trying to make a code where it displays all names in database where "clanwars" is set to 1 (int) and if all of them is 0 echo an message like: "Noone has signed up yet!"
This is some of the code i have:
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
while($row = mysqli_fetch_array($result))
{
if ($row['clanwars'] != '0') {
echo $row['mantra']."<br>";
} else {
echo 'Noone has signed up yet!';
}
}
mysqli_close($con);
First, in your example row['clanwars'] will never equal to 0 because you already specified WHERE clanwars = 1 in your query, so MySQL will return only those that have clanwars=1. If I understand well, you need to do something like:
<?
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
if (mysqli_num_rows($result)==0) echo 'Noone has signed up yet';
else {
while ($row = mysqli_fetch_array($result)) {
//do what you need
}
}
?>
So basically, you retrieve everyone who has CLANWARS set to 1 in the database. If there are records, process them, if there are no records, it means that nobody has signed up.
Is this what you need?
Try this:
$result = mysqli_query($con,"SELECT * FROM users WHERE clanwars = 1 ORDER BY mantra");
if (mysqli_num_rows($result) == 0)
{
echo 'Noone has signed up yet!';
}
else
{
while ($row = mysqli_fetch_array($result))
{
echo $row['mantra']."<br>";
}
}
mysqli_close($con);

php mysql if row is empty and if isn't empty

Code:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table`
WHERE `Username` = '$Username'
ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) { ?>
<?php if(!isset($db['article'] && $db['subject'])) {
echo "Your articles";
} else {
echo "You have no articles added!";
} ?>
<?php } ?>
So I want the rows for example(db['article'] and $db['subject']) from a specific username (see: $Username = $_SESSION['VALID_USER_ID'];) to echo the information if is not empty else if is empty to echo for example "You have no articles added!"
If is some information in the rows the code works, echo the information BUT if the rows is empty don't echo nothing, the code should echo "You have no articles added!" but this line don't appear, where is the mistake?
I tried for if !isset, !empty, !is_null but don't work.
I think what you're trying to achieve is:
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
if(mysql_num_rows($q) > 0)
{
echo "Your articles:\n";
while($db = mysql_fetch_array($q)) {
echo $db['subject']." ".$db['article']."\n";
}
}
else
{
echo "You have no articles added!";
}
?>
I don't understand. Do you have article rows with username, but without article, i.e.:
| id | user | article |
-------------------------------------
| 1 | X | NULL |
If so, you can test with:
if($db['article'] == NULL) { .... } else { .... }
Otherwise, if you don't have a row with user=x, when there are no record, mysql will return an empty result.
So, basicly, if no rows are found on selection: SELECT * FROM article_table WHERE Username = 'X';, you can test
if(mysql_num_rows($q) > 0) { .... } else { .... }
However, mysql_ functions are not recommended anymore. Look at prepared statements.
You have a logic error in your if statement -- what you want is to check if both the article and subject are set.
With your current code, you compare $db['article'] with $db['subject'], and check if the result is set. You need to change it a bit :
Instead of :
if(!isset($db['article'] && $db['subject'])) {
Try:
if(isset($db['article']) && isset($db['subject'])) ...
I would do something like this:
$articles='';
$Username = $_SESSION['VALID_USER_ID'];
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
if(isset($db['article']) && isset($db['subject'])) {
$articles .= $db['article']."<br/>";
}
}
if($articles != ''){
echo $articles;
}
else{
echo "No articles";
}
?>
fastest way to achieve what you want is by adding a variable that will verify if the query returned any rows:
<?php $Username = $_SESSION['VALID_USER_ID'];
$i = 0;
$q = mysql_query("SELECT * FROM `article_table` WHERE `Username` = '$Username' ORDER BY `id` DESC");
while($db = mysql_fetch_array($q)) {
$i = 1;
if(!isset($db['article'] && $db['subject'])) { echo "Your articles"; } ?>
<?php }
if ($i == 0) echo "You have no articles";
?>
You tried to echo "no articles" in the while loop, you get there only if the query returns information, that is why if it returns 1 or more rows, $i will become 1 else it will remain 0.
In your case:
$numArticles = mysql_num_rows($q);
if($numArticles > 0)
echo 'Your articles';
else
echo 'No articles :((((';
I recommend tough moving on to PDO to communicate with DB.

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

PHP Show next image in the table

I am showing an image on my page from the db table like this:
<?php
if ($db_found) {
$SQL = "SELECT * FROM myTable where id='$posted_id'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
echo '<img src="images/'.$db_field['image'].'" alt="" />';
}
mysql_close($db_handle);
}
?>
Next
How can I do so that if $posted_id is for example 1 ... when I click the "Next" link the image id = 2 appears and so on.
for that you need to either refresh page or use ajax.
you can pass variable posted_id in url like this.
Next
this way you can pass next id from database .. if your id falls in sequence.
you also need to programatically handle issue like what to do if record of next id does't exist in database..
You should work with the MySQL LIMIT and ORDER filters.
<?php
if (isset($_GET['current'])) {
$current = $_GET['current'];
} else {
$current = 0;
}
$request = "SELECT * FROM myTable ORDER BY id ASC LIMIT " . $current . ",1";
?>
And then, just to catch the next item, you can do something like that:
<?php
// make the last item point to the first one
$loop = true;
$count = "SELECT COUNT(*) FROM myTable";
if ($current < $count) {
$next = $current + 1;
} else if ($loop) {
$next = 0;
// no loop, then just stay at the end
} else {
$next = $current;
}
?>

Categories