echo one before the last table row from my database - php

this is my code that echo last table row . and i wanna echo one before the last table row together with this code . any body can help ?
i use this to show table parameters in my application
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//creating a query
$stmt = $conn->prepare("SELECT name,family FROM student_list;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result(
$t1,
$t2
);
$list = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['t1'] = $t1;
$temp['t2'] = $t2;
array_push($list, $temp);
}
//displaying the result in json format
echo json_encode($list);

You can use limit to get second last row of table.
SELECT name,family FROM student_list ORDER BY id DESC LIMIT 1,1

Related

How to use mySQL data in PHP for loop?

I'm trying to get the last ID from mySQL script and then use it in PHP for loop to display each product that way so I don't need to type separately each one of them, maybe it's not the best solution, but this is prototyping. The problem is that nothing shows on the page when it's run, if there is a number instead of $last_id then it works
<?php
$serverName = "localhost";
$username = "root";
$password = "";
$connection = new mysqli($serverName, $username, $password);
if($connection -> connect_error)
{
die("Connection failed: " . $connection -> connect_error);
}
$last_id = "SELECT id FROM tab_mobiteli ORDER BY id DESC LIMIT 1";
for($i = 0; $i < $last_id; $i++) {
echo "<p>This is text</p>";
}
?>
How can you be sure that you'll have ID's in perfect order. There could be a number in there that does not exist, since you can later delete some rows in the database. Anyway I usualy use PDO instead of mysqli but here's the idea. Just read everything and then you can play with the output in foreach loop.
$stmt = $connection->query("SELECT * FROM tab_mobiteli");
foreach ($stmt as $row) {
// here you do what you want to do for each db entry
// for example "echo $row['id'];"
}
You aren't executing the query this is why it will display nothing.
Here is an example of a query to a mysql db using PDO, read more about here.
<?php
$dbh = new PDO('mysql:dbname=test;host=localhost','root','root');
$stmt = $dbh->prepare("SELECT id FROM tab_mobiteli ORDER BY id DESC LIMIT 1");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($results) > 0){
for($i = 0; $i < count($results); $i++) {
echo "<p>$results[$i]['id']</p>";
}
}
?>

mysqli_fetch_array only displays the first result

I struggled all day to display the results of an SQL query using PHP.
I have a table in the database named coins with the following columns:
- nr_unic (which is the index);
- rank;
- name;
- symbol;
- price_usd;
- price_btc;
What I need to do is to fetch the values of each coin (from the name field) and display the symbol, price_usd, price_btc, and rank. The piece of code which contains the query I am running and trying to display the values is:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// SQL QUERY
$sql= "SELECT rank, name, symbol, price_usd, price_btc, 24h_volume_usd FROM coins WHERE rank BETWEEN 1 AND 10 ORDER BY nr_unic DESC LIMIT 10";
$result = $conn->query($sql);
$rows = array();
if ($result) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . $row['price_usd'] . " " . $row['symbol'] . " " . $row['rank'];
foreach ($rows as $key => $value) {
echo $value;
}
}
mysqli_free_result ($result);
}
Thank you!
LATER EDIT
Following #Máté Solymosi indications I managed updated the code and to display the results. The problem now is they are getting duplicated: I get the first coin, then the first and the second, then the first, second and third... and so on.
The code I use was updated
The return statement in your while loop causes the function to terminate immediately, returning just the first row. Instead, you should collect the results in an array and return the array at the end:
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$rows[] = $row['name'] . " " . // ...
}
mysqli_free_result($result);
return $rows;

Why is my update statement updating my columns with the wrong data?

Why is my update statement updating my columns card_id with the wrong data?
My database structure.
$deckCardIds Holds a array of different two digit numbers.
What I expect the code to: Update each column based on the the current row I am looping through and updating card_id with the current index of $deckCardIds.
What is actually happening: The columns are looped through and data is set with $deckCardIds but then set to 0 when the loops moves to the next iteration.
<?php
$playerId=$_GET['playerid'];
$playerDeckCardIds=$_GET['deckcardids'];
$deckCardIds = explode(" ", $playerDeckCardIds);
array_pop($deckCardIds);
try
{
#Connect to the db
$conn = new PDO('mysql:host=localhost;dbname=tcg', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT row_id FROM player_deck WHERE player_id = :player_id');
$stmt->execute(array('player_id' => $playerId));
$r = $stmt->fetchAll(PDO::FETCH_OBJ);
$i=0;
foreach($r as $row)
{
$stmt = $conn->prepare('UPDATE player_deck SET card_id = :card_id WHERE row_id = :row_id');
$stmt->bindParam(':card_id', $deckCardIds[$i]);
$stmt->bindParam(':row_id', $row->row_id);
$stmt->execute();
$i++;
}
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
?>

php-mysql How to select the particular number of the row in mysql?

I am new at this and learning the code.
I want to create the php code which select the particular row.
say 5th row or 6th row any row.
I create the code like this
<?php
$servername = "localhost";
$username = "test1";
$password = "pass";
$dbname = "test1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FIELD1, FIELD2 FROM mytable ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["FIELD1"]. " - Name: " . $row["FIELD2"]. " <br>";
}
} else
{
echo "0 results";
}
$conn->close();
?>
THis code works fine but it give the all data of the table.I want to just select particular row number data.how to do this??
You can do it with the LIMIT statement, say LIMIT 3,1 to select the 4th row. First number is the starting row, second number is the count of rows to select.
$sql = "SELECT FIELD1, FIELD2 FROM mytable LIMIT $row_index, 1";
will give you row $row_index + 1
You can do it using WHERE condition in query as SELECT FIELD1, FIELD2 FROM mytable WHERE id = 1.

mySQL statement not running in PHP variable declaration

In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!

Categories