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>";
}
}
?>
Related
This question already has answers here:
mysqli ignoring the first row in a table
(4 answers)
Closed 1 year ago.
I trying to get the latest orders in my database and show in php frontend.
The problem is when i print the data, the first element in the array is not appear.
Example code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDatabase";
$db = new mysqli($servername, $username, $password, $dbname);
$counter = 0;
$query = "SELECT * FROM `orders` WHERE `supplier` = '".session('email')."' ORDER BY `id_order` DESC";
if ($result = $db->query($query)){
if($result->num_rows > 0) {
$row = $result->fetch_assoc();
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
$name = $row["name"];
$orderID = $row["id_order"];
$ordersArray[] = array('id_order'=> $orderID,
'name'=> $name, );
}
foreach($ordersArray as $row){
if( $counter <= 4 ){
echo ($row["name"]);
echo ($row["id_order"]);
$counter = $counter + 1;
}
}
} else {
echo ('<tr><td>No tienes ordenes recientes</td></tr>');
}
}
$db->close();
Example output
4
3
2
1
I have a fifth value in the database that should be displayed first, but it does not appear
You fetch the first row already before the while loop starts...
$row = $result->fetch_assoc(); // << first row feteched here
$ordersArray = array();
// Set orders data to ordersArray
while($row = $result->fetch_assoc()){
Remove the random fetch:
$row = $result->fetch_assoc();
Making this call moves the result pointer up but you're not adding this row to $ordersArray.
Alternatively, if for some reason you do need to access the first row outside your while loop, either add the data to the new array or use $result->data_seek(0) to reset the pointer.
I started learning PHP and Databases today.
What I tried so far and worked is to access information from a database using a simple updateScores.php file.
DB high_scores:
names | scores |
___________________
player1 | 20 |
player2 | 69 |
My code:
$host="localhost";
$database="players";
$user="root";
$password = "";
$error = "Cant connect";
$con = mysqli_connect($host, $user, $password);
mysqli_select_db($con, $database) or die("Unable to connect!");
$query = "SELECT * FROM high_scores";
$result = mysqli_query($con, $query);
$n = mysqli_num_rows($result);
for($i=0; $i<$n; $i++){
$name = mysqli_fetch_assoc($result)["name"];
$score = mysqli_fetch_assoc($result)["score"];
echo "Name : ".$name;
echo "Score : ".$score;
}
?>
This works fine when i execute http://localhost/updateScores.php
However when i change the last two lines to
echo $name."\t";
echo $score."\n";
I only get the first name (player1) and the last score (69)
Why this is happening? Any help and additional link would be great. Thanks.
Your problem is that your for loop has two calls to mysqli_fetch_assoc, each of which fetches a new row from the database:
$name = mysqli_fetch_assoc($result)["name"];
$score = mysqli_fetch_assoc($result)["score"];
So you will end up getting the name from one row with the score from the next. The normal way of writing this loop is using while, with the fetch as the condition for the loop and then accessing the individual values from the fetched row:
while ($row = mysqli_fetch_assoc($result)) {
$name = $row["name"];
$score = $row["score"];
echo "Name : ".$name;
echo "Score : ".$score;
}
MySQLi result is traversable. You could simply use foreach.
$result = mysqli_query($con, $query);
foreach($result as $row) {
echo "Name : ".$row['name'];
echo "Score : ".$row['score'];
}
I have a PHP script that queries the database and returns a list of all the usernames in my database. Problem is, it is not printing anything and I think I am doing the while statement incorrectly, this is my code below:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="Ben"{
echo "Here";
}
//$count++;
}
?>
Even something as basic as this doesn't work:
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = $dbcon -> prepare($stmt);
$result->execute();
$result->store_result();
$count = 0;
while($row = mysqli_fetch_assoc($result)){
echo "Here";
//$count++;
}
?>
I can't also seem to increment the count too and it is not even printing the basic "Here"
The main problem is that you are not reading manual/examples properly.
mysqli_stmt_get_result() doesn't change the state of a statement. It returns a mysqli result. So you have to assign this returned value to a variable and than use this one.
Besides, you are using a database completely wrong way. Instead of selecting all rows from database you should always select the only data you need.
For your case the code would be like this.
include "init.php";
$name = "Ben";
$stmt = $dbcon->prepare("SELECT 1 FROM tbl_users WHERE username = ?");
$stmt->bind_param("s", $name);
$stmt->bind_result($found);
$stmt->execute();
$stmt->fetch();
if ($found) ... // here you go
For other cases you have to read the manual or a book carefully. and reproduce the code exactly.
Since there are multiple error in your code i managed to write a code am not sure following is best but it works
<?php
include "init.php";
$stmt = "SELECT username FROM tbl_users ";
$result = mysqli_query($sqlconnection, $stmt) or die($mysqli_load->error);
$count = 0;
while($row = mysqli_fetch_assoc($result)){
if($row['username']=="ben"){
echo "Here";
}
//$count++;
}
?>
few errors i found in your code are ) is missing here if($row['username']=="Ben"{ next to "ben"){
and use this type of connection
$link = new mysqli("localhost","user","pass","database");
I want to display data from all rows only for the column named 'text_notes' from my db.
And I want to loop that data in a p tag so that all data from column text_notes is displayed one by one till the end.
Below is the code I tried but it displays all the columns of the latest row and doesn't display the other rows.
I want the data from column 'text_notes' from all the rows to be displayed from latest at the bottom to the oldest at the top.
<?php
$query = "SELECT * FROM notes";
$conn = new mysqli(DBROOT,DBUSER,DBPASS);
$conn->select_db(DBNAME);
if ($conn == TRUE) {
$runQuery = $conn->query($query);
$resultNum = $runQuery->num_rows;
$result = $runQuery->fetch_array();
$resultRow = mysqli_fetch_row($runQuery);
$notes = $result['text_notes'];
for ($i = 0; $i < $resultNum;) {
echo "<p>".$resultRow[$i]."</p>";
$i++;
}
}
?>
$mysqli = new mysqli(DBROOT, DBUSER, DBPASS, DBNAME);
$query = "SELECT text_notes FROM notes";
$result = $mysqli->query($query, MYSQLI_STORE_RESULT);
// Cycle through the result set
$counter = 0;
while(list($text_notes) = $result->fetch_row())
echo "<p>";
$counter++;
echo $counter . " : ";
echo " $text_notes </p>";
// Free the result set
$result->free();
I think it works :) Thanks
I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).