Get id of last post displayed in table - php

In code below I will be displaying posts in table. Now for creating load more function I need to get id of last post in table but I am not able to do that, Here $ID = $row['id']; gets me id of first post may be because it's outside loop and to get id of last post I must place this code inside loop. But where to exactly place it so that I get id of last post displayed in table.
<?php
$sql = "SELECT * FROM posts ORDER BY id desc limit 3";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
?>
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div><h2><?php echo $row['title']; ?></h2></div>
<div><p><?php echo $row['body']; ?></p></div>
<img src='<?php echo $row['pic']; ?>'>
<div><p><?php echo $row['about']; ?></p></div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>

Try this code :-
$ID1 = $row[0]['id'];//first id of table
$ID2 = $row[1]['id'];//2 id of table
$ID3 = $row[2]['id'];//3 id of table
get latest id:-
$sql = "SELECT * FROM posts ORDER BY id desc limit 1";

Try This Query
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");
try {
$dbh->beginTransaction();
$tmt->execute( array('user', 'user#example.com'));
$dbh->commit();
print $dbh->lastInsertId();
} catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
}
} catch( PDOExecption $e ) {
print "Error!: " . $e->getMessage() . "</br>";
}
?>

Related

How to get variable from header in multi query?

i already had forms where I got the variable from the header but the forms have always been pdo and always one single query. This form is connected via mysqli and I just can't figure out how to get a variable.
<?php
$mysqli = new mysqli("localhost:3307", "root", "root", "test");
if($mysqli->connect_errno)
die ("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM contacts WHERE id = ?;";
$query .= "SELECT * FROM companies WHERE id = ?;";
if($mysqli->multi_query($query)) {
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
echo"<table border ='1'>";
echo "<tr>";
foreach($finfo as $f) {
echo "<th>".$f->name."</th>";
}
echo "<br>";
echo "<br>";
echo "</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
foreach($row as $v) {
echo "<td>".$v."</td>";
}
echo "</tr>";
}
} while ($mysqli->more_results() && $mysqli->next_result());
}
?>
So the column "id" in both tables is the PK/FK and I want to retrieve information where id = ?.
How do I get the ? variable from the header and pass it on?
I feel like in my past tries I got the variable successfully with this code
$id=isset($_GET['id']) ? $_GET['id'] : die('ERROR: Record ID not found.');
[...]
$statement = $mysqli->prepare($query);
$statement->bindParam(1, $id);
$statement->execute();
but didn't echo it correctly.
Thank you in advance!

Cannot get URL from Database to link

I am doing a project and would be eternally grateful for help in getting my URl's to link. I have tried looking around to no avail. I have a database (4columns). The last one (link1) should link to videos with the specified URL.When the table comes up the URL's are not clickable (is there a way to simplify this say "click me"?). Here is my code. I've also attached an image of the table. This is really busting my brains, thanks.
<?php
$con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Table output
Try this:
<?php
$sql = "SELECT * FROM `videos`";
$result = mysqli_query($con, $sql);
?>
<table>
<?php
while($row = mysqli_fetch_assoc( $result)) {
?>
<tr>
<td><?php echo $row['topic1'];?></td>
<td><?Php echo $row['subject1'];?></td>
<td><a href="<?php echo $row['link1']; ?>" target="_blank">Click me</td>
</tr>
<?php } ?>
<table>
Or you can also use do while loop:
do{
echo '<tr>';
echo '<td>'.$row['topic1'].'</td>';
echo '<td>'.$row['subject1'].'</td>';
echo '<td><a href="'.$row['link1'].'" target="_blank">Click me</td>';
echo '</tr>';
} while($row = mysqli_fetch_assoc( $result);
I added the target attribute to open the link in a new window.
I looked at your code and i found a couple errors.
change $con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test"); to $con = new mysqli("localhost", "feedb933_charles", "pass100", "feedb933_test");
Then change if (mysqli_connect_errno()) to if (mysqli_connect_error()) {
Then change
$sql = "SELECT * FROM videos";
to
$sql = "SELECT topic1, subject1, link1 FROM videos";
or if you want to select one row
$differentvalue = ""; // value to run
$sql = "SELECT topic1, subject1, link1 FROM videos WHERE difvalue = ?";
difvalue is the value different frm the rest so the php code knows what to grab.
Using stmt means no sql injection
Add:
$stmt = $con->stmt_init();
if (!$stmt->prepare($sql))
{
print "Failed to prepare statement\n";
}
else
{
}
Then in side if (something) { } else { IN HERE }
(if you have WHERE diffvalue) Add:
$stmt->bind_param("s", $differentvalue); // $stmt->bind_param("s", $differentvalue); if text, $stmt->bind_param("i", $differentvalue); if integer
Then
Add:
$stmt->execute();
$list = $stmt->fetchAll();
then outside the if (something) { code } else { code }
Add:
echo "<table><tr><th>topic1</th><th>subject1</th><th>link1</th></tr><tr>";
foreach ($list as $row => $new) {
$html = '<td>' . $new['topic1'] . '</td>';
$html .= '<td>' . $new['subject1'] . '</td>';
$html .= '<td>' . $new['link1'] . '</td>';
echo $html;
}
echo "</tr></table>";
If you are still having problems goto the links listed
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-result.fetch-all.php
Hope this helps
<?php
$con=mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
*//this href will give u the link as u asked. //be sure you store proper url. In case of exact video name saved in column thn can make the url for your web output. //ex:<a href="http://example.com/'.$link.'.extension">*
</tr>";
}
echo "</table>";
mysqli_close($con);
?>

Two near-identical pieces of code.. one works, the other doesn't

The following code works fine, it randomly selects an image from a folder, and assigns it as a background to a generated Div. This works. If I use this code a second time, but use it to simply place an img-src of the randomised image, this also works. However, using the code in the same way as the first, breaks the site. What am I doing wrong?
<!-- BEGIN FEATURED 1 -->
<?php
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo $e->getMessage();
echo 'Could not establish a connection to the database.';
}
$query = $conn->prepare('SELECT `articleid`,`title` FROM `news_articles` WHERE featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
'N'
);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}
$image = get_rand_img('images/featured_images/csgo/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image" style="height: 267px; width: 292px; background:url(/images/featured_images/csgo/<?php echo $image ?>)">
<?php
$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
$result->execute();
$rows = $result->fetch();
echo '<div class="featuredtitle1">';
echo $rows['short_title'];
echo '</div>';
echo '</div>';
echo '</a>';
?>
The code below, breaks the site.. (I have commented it out at the moment as you can see).
<!-- BEGIN FEATURED 2 (Disabled) -->
<?php
/*
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch (PDOException $e) {
echo $e->getMessage();
echo 'Could not establish a connection to the database.';
}
$query = $conn->prepare('SELECT `articleid` FROM `news_articles` WHERE featured = 1 ORDER BY RAND() LIMIT 1');
$array = array(
'N'
);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
foreach ($results as $row) {
}
$image = get_rand_img('images/featured_images/dota/');
$title = $result['title'];
echo '<a href="index.php?viewarticle=1&articleid=' . $row . '">';?>
<div id="featured-image2" style="height: 267px; width: 292px; background:url(/images/featured_images/dota/<?php echo $image ?>)">
<?php
$result = $conn->prepare("SELECT `articleid`,`title`,`short_title` FROM `news_articles` WHERE articleid=$row");
$result->execute();
$rows = $result->fetch();
echo '<div class="featuredtitle2">';
echo $rows['short_title'];
echo '</div>';
echo '</div>';
echo '</a>';
*/
?>
I don't understand why the first piece of code is fine, but duplicating it again breaks it?
Before you edited your comment, I saw a fatal error about accessing object as an array. Try to change your code from this:
$results = $query->fetchAll(PDO::FETCH_COLUMN, 0);
To this:
$results = $query->fetchAll(PDO::FETCH_ASSOC);

$_Get not getting url id

*fixed****
echo "<li>" . $row['iname'] . "</li>";
what is missing ?
.php
/facepalm
I can't seem to get the id value to pass to the $_GET. I've tried adding sessions and all kinds of stuff.
Even when I just do a print_r($GET) by itself it gives me :
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for
this address in a way that will never complete
This is not for production, but a project so I'm not to worried about injections ect..
I've use GET with old php mysql syntax and it works, just not sure what the problem is. Alos no the code is barbaric so any help would be greatly appreciated.
Page 1 :
<?php
require('lib/inc/db_inc.php');
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE items.itype = 'usb_controllers'";
$stmt = $db->query($sql);
while ($row = $stmt->fetch()){
$id = $row['itemID'];
echo "<div class=\"prodMain\">";
echo "<div class=\"img\">";
echo "<img src=\"" . $row['imgURL'] ."\"/>";
echo "</div>";
echo "<ul>";
echo "<li>" . $row['iname'] . "</li>";
echo "<li>" . $row['idesc'] . "</li>";
echo "<li>" . $row['iprice'] . "</li>";
echo "</ul>";
echo "</div>";
}
?>
page 2 :
<?php
require('../lib/inc/db_inc.php');
if (!isset($_GET['id'])) {
die("missing query parameter");
}
$id = intval($_GET['id']);
if ($id === '') {
die("Invalid query parameter");
}
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice,iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
$row = $stmt->fetch();
echo print_r($row);
?>
db_inc.php
<?php
try {
$db = new PDO('mysql:host=******;dbname=*****', '*********', '********');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
This statement
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = '$id'";
$stmt = $db->query($sql);
has a vulnerability for SQL Injection. See here.
So you should rewrite it like
$sql = "SELECT items.itemID, items.iname, items.idesc, items.iprice, iimg.imgURL FROM items JOIN iimg ON items.itemID = iimg.pid WHERE itemID = ?";
$stmt = $db->prepare($sql);
$stmt->execute(array($_GET['id']));

Function prepare() on a non-object error

I have looked up the error for this and I think I am calling the statement before for it to be initialized. I have made a simple connection class that I can include into all of my files that will be talking to the mysql server. Knowing how I am with things, I am most likely over thinking things. I cant seem to find what I am doing wrong.....
Top part of the code is cut off as it only contains the HTML head and php starting code that is non-important for this.
//include database connection
include('connection.php');
$action = isset($_GET['action']) ? $_GET['action']: "";
if($action=='delete'){ //if the user clicked ok, run our delete query
try {
$query = "DELETE FROM sc_steamgames WHERE appid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_GET['appid']);
$result = $stmt->execute();
echo "<div>Record was deleted.</div>";
}catch(PDOException $exception){ //to handle error
echo "Error: " . $exception->getMessage();
}
}
//select all data
$query = "SELECT * FROM sc_steamgames";
$stmt = $con->prepare( $query );
$stmt->execute();
//this is how to get number of rows returned
$num = $stmt->rowCount();
echo "<a href='add.php'>Create New Record</a>";
if($num>0){ //check if more than 0 record found
echo "<table border='1'>";//start table
//creating our table heading
echo "<tr>";
echo "<th>AppID</th>";
echo "<th>Title</th>";
echo "<th>Release Date</th>";
echo "<th>Last Updated</th>";
echo "</tr>";
//retrieve our table contents
//fetch() is faster than fetchAll()
//http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//extract row
//this will make $row['firstname'] to
//just $firstname only
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td>{$appid}</td>";
echo "<td>{$title}</td>";
echo "<td>{$releasedate}</td>";
echo "<td>{$lastupdate}</td>";
echo "<td>";
//we will use this links on next part of this post
echo "<a href='edit.php?id={$appid}'>Edit</a>";
echo " / ";
//we will use this links on next part of this post
echo "<a href='#' onclick='delete_user( {$appid} );'>Delete</a>";
echo "</td>";
echo "</tr>";
}
echo "</table>";//end table
}else{ //if no records found
echo "No records found.";
}
?>
<script type='text/javascript'>
function delete_user( appid ){
//this script helps us to
var answer = confirm('Are you sure?');
if ( answer ){ //if user clicked ok
//redirect to url with action as delete and id to the record to be deleted
window.location = 'index.php?action=delete&id=' + appid;
}
}
</script>
</body>
</html>
connection.php
/* Database Info */
// Host/IP
$host = "localhost";
// Database Name
$db_name = "**";
// Username
$username = "**";
//Password
$password = "**";
/* End Database Info */
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
echo "Connection error: " . $exception->getMessage();
}

Categories