Grab min value in PHP from MySQL Database? - php

So I have some numbers that take the name "id" in my MySQL database. I tried this code:
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo min($id);
}
On the last line I tried to echo the min value for id, but it didn't work. Any suggestions?
ANSWER: Use "ASC LIMIT 1"
while($row = mysql_fetch_assoc($sql)){
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}

$sql = mysql_query("SELECT * FROM users ORDER BY id ASC LIMIT 1");
while($row = mysql_fetch_assoc($sql))
{
$id=$row['id'];
$user = $row['usrname'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<strong>User:</strong> ".$user." ".$fname." ".$lname."<br/>";
echo $id;
}

Try this:
$sql = 'SELECT min(id) as min FROM users';
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
$min_id = $row['min'];

In case you cannot change the query order (sort by names?), you can determine the lowest $id by using a helper variable:
$min = isset($min) ? min($min, $id) : $id;
And then print $min; after your loop.

If not able to use MIN() in MySQL, try this...
$smallestId = -PHP_INT_MAX;
while($row = mysql_fetch_assoc($sql)) {
...
$smallestId = min($smallestId, $id);
}
If you never have any negative ids (you shouldn't), you could just change -PHP_INT_MAX to 0.

Related

MySQL Multi Query store result second query

I am querying from two different tables in the database here and I can store the values from the first query but how do I store the information from the second query?
$query = "SELECT * ";
$query .= "FROM user_account ";
$query .= "WHERE user_id = $user_id ";
$query .= "SELECT * ";
$query .= "FROM user_profile ";
$query .= "WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_row($result)) {
$Firstname = $row['Firstname'];
$Lastname = $row['Lastname'];
$Email = $row['Email'];
$Birthday = $row['Birthday'];
$Address = $row['Address'];
$Zip = $row['Zip'];
$City = $row['City'];
$State = $row['State'];
$Country = $row['Country'];
$Avatar = $row['Avatar']; Will be added later
$Phone = $row['Phone'];
$Website = $row['Website'];
$Member_level = $row['Member_level'];
}
mysqli_free_result($result);
}
if (mysqli_more_results($mysqli)) {
}
while (mysqli_next_result($mysqli)) ;
}
}
Just the usual way
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$account = $mysqli->query($query)->fetch_assoc();
$query = "SELECT * FROM user_profile WHERE user_id = $user_id ";
$profile = $mysqli->query($query)->fetch_assoc();
as simple as that.
I am really wondering why PHP users are inclined to writing SO MUCH code and to using so much intricate ways for the most trifle operations
On a side note, in your particular case you can write a single JOIN query.
In your code, why are you using mysqli_free_result function because it will frees the memory associated with a result object so when while loop run it will not show any result.
$query = "SELECT * FROM user_account WHERE user_id = $user_id ";
$query .= "SELECT * FROM user_profile WHERE user_id = $user_id ";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_assoc($result)) {
var_dump($row); //for checking result
// Now use array to show your result
}
} }while (mysqli_next_result($mysqli)) ;
You should always free your result with mysqli_free_result(), when
your result object is not needed anymore.

Most efficient way to echo PHP prepared statements

I have an SQL query which I have recently turned into a prepared statement for security purposes. I have a query which returns many rows, each consisting of many columns. My question is how to echo the results using a while loop. My example I have so far:
$stmt = $conn->prepare("SELECT * FROM Customers
WHERE travel_Date >= ?
AND travel_Date <= ?
".$searchOption."
LIMIT ?
OFFSET ?");
$todayDateFrom = $todayDate." 00:00:00";
$todayDateTo = $todayDate." 23:59:59";
$stmt->bind_param("ssii", $todayDateFrom, $todayDateTo, $limit, $offset);
$stmt->execute();
while ($stmt->fetch()) {
//echo first name
//echo surname
//echo address
//echo number
//echo type
//15 other things i need to print off
}
I'm not sure what the best way to do this is. I have thought about:
$stmt->bind_result($firstName, $surname, $address, //etc);
But I'm wondering if there's another alternative similar to unprepared statements:
while($row = mysqli_fetch_array($query)){
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
//etc
}
try this:
$result = $stmt->get_result();
while ($row = $result->fetch_array())
{
echo $row['firstName'];
echo $row['surname'];
echo $row['address'];
}
try this -
$result_arr = array();
while($row = $stmt->fetch()){
$record = array();
$record['firstname'] = $row['firstname']; // if your db column contains firstname column other wise you can also use $row[0];
$record['name'] = $row[1]; // end so on .......
$result_arr[] = $record;
}
hope this will work for u...

php mysqli not returning value

Here is the code that is giving me a problem:
$letter = $_POST['artistButton'];
$result = $mysqli->query("SELECT * FROM `Generic` WHERE `songName` LIKE '$letter%'");
$row = $result->fetch_array();
while ($row = $result->fetch_array()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}
The statement is correct I saved it to a variable and printed it to the screen, then ran it from the database and it printed the results I wanted so it definitively is not that. For some reason though it is not displaying. I am guessing it has something to do with something I messed up converting from mysql to mysqli. Thanks -Sam
Clearly some codes are cut, but try to remove that extra:
$row = $result->fetch_array();
And use:
while($row = $result->fetch_assoc()) {
Since you're interested on associative indices anyway.
Important note: Since you're using mysqli_*, use its parameterized queries instead. Don't directly use $_POST values on the query.
$letter = "{$_POST[artistButton]}%";
$stmt = $mysqli->prepare('SELECT * FROM `Generic` WHERE `songName` LIKE ?');
$stmt->bind_param('s', $letter);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}

How to use parameters in url php?

I have a number pages namely
change=1.php
change=2.php
change=3.php
They all have similar coding but leaving 1 or 2 variable values.
And I know its a very bad idea! How can I make a link work like below:
change.php?id=1
change.php?id=2
change.php?id=3
http://oi62.tinypic.com/708gfm.jpg
<?php
include 'connection.php';
session_start();
include 'details.php';
/*$pkmn_id = $_SESSION['pkmn_id'];
$poke = $_SESSION['path'];*/
$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE team = 1 AND user_id = '".$id."' ");
while($rows = mysql_fetch_array($data))
{
$rep_id = $rows[0];
$pkmn_id = $rows['pkmn_id'];
$path = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' ");
$poke = mysql_result($path, 0, "path");
echo $poke;
echo "<br />";
$level = $rows['level'];
echo $level;
echo "<br />";
$exp = $rows['exp'];
echo $exp;
echo "<br />";
echo "<br />";
}
$data = mysql_query(" SELECT * FROM user_pokemon_db WHERE user_id = '".$id."' AND team = 0");
while($rows = mysql_fetch_assoc($data))
{
$db_id = $rows['id'];
$array[] = $db_id;
$level = $rows['level'];
$array1[] = $level;
$exp = $rows['exp'];
$array2[] = $exp;
$pkmn_id = $rows['pkmn_id'];
$data1 = mysql_query(" SELECT * FROM pokemons WHERE pk_id = '".$pkmn_id."' ");
while($rows = mysql_fetch_assoc($data1))
{
$poke = $rows['path'];
$array3[] = $poke;
}
}
$team = 1;
$_SESSION['team'] = $team;
$_SESSION['rep_id'] = $rep_id;
?>
My PHP code.
You probably want to use GET variables, for which you need to combine all the files into one, named change.php. In this file you need the line $foo = $_GET["id"] which will get the value of the variable "id" in the url change.php?id=1.
if (isset($_GET["id"])) {
$foo = $_GET["id"];
//your code here
}else{
echo 'ERROR!!! No id in URL';
}
You can have several variables in the URL like this: change.php?id=1&a=bar&b=toofoo
You can get current script's file name and parse integer.
__FILE__
gives current script's name. Then,
$myStr = preg_replace('/\.php$/', '', __FILE__);
$result = preg_replace('/change=$/', '', $myStr);
echo $result; // it's your id

SQL query not showing more than 1 row

This is the entire code the error must be in query 3 or 4. As you can see query 3 just gets info to build query 4 which should return the results.
I've got query 1 & 2 working ok which have the correct data showing.
<?php
session_start();
//printf('<pre>%s</pre>', print_r($_SESSION, true));
require('includes/config.inc.php');
require('includes/session.php');
//WORKING
DB_Connect();
$query = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'product' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result = mysql_query( $query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$hash = $row['hash'];
$foreignid = $row['foreign_id'];
$qty = $row['cnt'];
}
$query2 = "SELECT * FROM food_delivery_products WHERE food_delivery_products.id = ".$foreignid."";
$result2 = mysql_query( $query2) or die(mysql_error());
while($row = mysql_fetch_array($result2))
{
$name = $row['name'];
$description = $row['description'];
}
//---------------------------------------------------------------------------------------------------------------
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3)or die(mysql_error()) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
}
$query4 = "SELECT * FROM food_delivery_extras WHERE food_delivery_extras.id = ".$foreignidextra."";
$result4 = mysql_query( $query4) or die(mysql_error());
while($row = mysql_fetch_array($result4))
{
$nameextra = $row['name'];
}
echo $nameextra;
echo $qtyextra;
DB_Disconnect();
//$products = implode(", ",$_SESSION['pdf_quote']['product_arr']);;
//print $products
?>
print $row; is only valid inside the loop if you want to print all of them. Otherwise it will print only the last $row. Make it
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print $row;
}
its because you are printing the $row after the while loop gets executed
So it only prints the final result set
Use something like this instead:
$query3 = "SELECT * FROM food_delivery_orders_items WHERE food_delivery_orders_items.type = 'extra' AND food_delivery_orders_items.order_id=".$_SESSION['pdf_quote']['id']."";
$result3 = mysql_query( $query3) ;
while($row = mysql_fetch_array($result3))
{
$foreignidextra = $row['foreign_id'];
$qtyextra = $row['cnt'];
print_r($row);
}
you can also use the var_dump($row); instead of print_r($row);
this will output all the values stored in the $row array each time the loop iterates

Categories