Using result of one MySQL query as variable in another MySQL query - php

I'm trying to show the result HTML table based on team name
I'm able to echo right team name but unable to use it into a variable in my 2nd query I'm not able to find out what I'm doing wrong here why the query result is not visible. do I need to change something in my code?
<?php
include_once("connection.php");
$sql = "SELECT TeamName FROM `superuser` WHERE id = '303016'";
$queryRecords2 = mysqli_query($conn, $sql) or die("error to fetch employees data");
while ($row2 = $queryRecords2->fetch_assoc()) {
echo $row2['TeamName']."<br>";
}
if(isset($_POST['search']))
{
$valueToSearch = $row2['TeamName'];
$valueToSearch2 = $_POST['valueToSearch2'];
$valueToSearch3 = $_POST['valueToSearch3'];
$sql = "SELECT * FROM `dailydata` WHERE TeamName = '".$valueToSearch."' and Date BETWEEN '".$valueToSearch2."' AND '".$valueToSearch3."'";
$queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
else {
$sql = "SELECT * FROM `dailydata` WHERE TeamName = ''";
$queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
?>

For security purposes you should use prepared statements or even better you should use PDO instead of mysqli.
to fix this issue simply assign the value of $valueToSearch variable inside the loop.
<?php
include_once("connection.php");
$sql = "SELECT TeamName FROM `superuser` WHERE id = '303016'";
$queryRecords2 = mysqli_query($conn, $sql) or die("error to fetch employees data");
$valueToSearch;
while ($row2 = $queryRecords2->fetch_assoc()) {
$valueToSearch = $row2['TeamName'];
}
if(isset($_POST['search']))
{
$valueToSearch2 = $_POST['valueToSearch2'];
$valueToSearch3 = $_POST['valueToSearch3'];
$sql = "SELECT * FROM `dailydata` WHERE TeamName = '".$valueToSearch."' and Date BETWEEN '".$valueToSearch2."' AND '".$valueToSearch3."'";
$queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
else {
$sql = "SELECT * FROM `dailydata` WHERE TeamName = ''";
$queryRecords = mysqli_query($conn, $sql) or die("error to fetch employees data");
}
?>

Related

How to get result from query and insert the results in other table?

I did query to the database where I need the results from it and then store it in a variable. Then I will pass the variable to the INSERT INTO statement but for some reason my code does not work. This is my code/
$query = "SELECT * from animals where old= 1 AND user_id=".$_SESSION['user_id'];
$result = mysqli_query(mysqli_connect("","","", ""), $query);
while ($row = mysqli_fetch_array($result))
{
$variable[] = $row['number'];
}
//now I will pass the $variable to the INSERT INTO statement
if(isset($_POST['submit_d']))
{
foreach($variable as $var)
{
$query="INSERT INTO selectedanimals(number) VALUES ({$var},2)";
mysqli_query($con, $query) or die (mysql_error());
}
?>
<script>
alert("Animal added.");
self.location="chooseAnimals.php";
</script>
<?php
}
?>
You can use INSERT INTO ... SELECT for this purpose in a single query:
INSERT INTO selectedanimals (number)
SELECT number
FROM animals
WHERE old = 1 AND user_id = some_id
PHP code:
$query = "INSERT INTO selectedanimals (number) ";
$query.= "SELECT number FROM animals WHERE old = 1 AND user_id = ".$_SESSION['user_id'];
mysqli_query($con, $query) or die (mysql_error());

Error when adding FIRST record to table

Ok. I ran into an issue. My code is able to insert records into my merchandise table. I truncated the table and a record is still inserted into the table but with an error "Undefined variable last_id". I assume that this is because when the table was truncate, there isn't a previous id since the record being inserted is the FIRST. Can someone help me resolve this issue. Thanks!
$sql = "SELECT m_id FROM merchandise";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)) {
$last_id = $row["m_id"];
}
$next_id = $last_id+1;
$conc = number_format($next_id/100,2,'-','');
$query = "INSERT INTO merchandise (mfr,type,description,mer_sku,price,qty) ";
$query .="VALUES ('$mfr','$type','$desc','MR{$mfr}{$conc}','$price','$qty')";
$add_sku_query = mysqli_query($connection, $query);
Declare last id as zero in case there are no rows.
$last_id = 0;
$sql = "SELECT m_id FROM merchandise";
$result = mysqli_query($connection, $sql);
while($row = mysqli_fetch_assoc($result)) {
$last_id = $row["m_id"];
}
$next_id = $last_id+1;

Using a good SQL query instead of PHP code

I have a page that is taking a kind of long time to load, and I'm almost sure that this is caused by too many sql requests (AKA caused by my bad SQL skills). Is there anyway to join these 3 queries into one?
What I want to do with this query is to try to select a specific id from cardapios and, if there is anything there (if $num_rows > 0) the only thing I want to do is select that id. If there is nothing there, then I want to insert something and then select the id of that.
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
$query = "SELECT id FROM cardapios WHERE nome='$nome' ";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
}
}
I am trying to put all of this into one query but getting nowhere. Is there anyway to use just one query for doing all of this?
Thanks in advance!
You can replace the last query by getting the mysqli_insert_id($con); as you already have the insert id available after the insert
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}
}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
if ( $sql !== false) { // did insert work
$_SESSION['id_cardapio'] = mysqli_insert_id($con);
} else {
// insert did nto work??
}
}

MySQL AVG function returning 0

I'm using the code below to query the database.
mysql_query ("SELECT * FROM _$symbol ORDER BY date DESC;");
$_10day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 10;");
$_21day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 21;");
$_50day = mysql_query ("SELECT AVG(close) FROM _$symbol limit 50;");
echo "$_10day\n";
echo "$_21day\n";
echo "$_50day\n";
mysql_query ("INSERT INTO _$symbol(_10day) VALUE ('$_10day');");
echo mysql_errno($sql) . ": " . mysql_error($sql). "\n";
I need to get the average of close from the database, and I'm using the AVG()function, then insert the return value into the database. The queries work in mysql however they do not work through the script. It does enter a value into the database, but it always enters 0. What am I doing wrong?
EDIT--solution found
$get10 = mysql_query ("SELECT AVG( close ) AS CloseAverage from ( SELECT close FROM _$symbol ORDER BY date DESC limit 10 ) sub1 ;");
$row = mysql_fetch_assoc($get10);
$_10day = $row['CloseAverage'];
if (!mysql_query ("UPDATE _$symbol SET _10day = $_10day, _21day = $_21day, _50day = $_50day, _100day = $_100day, _120day = $_120day, _150day = $_150day, _200day = $_200day, _240day = $_240day, _20dayVol = $_20dayVol, _50dayVol = $_50dayVol where date = '$date';"))
{
echo "Update query failed";
}
I was querying it incorrectly apparently it needed to be selected as a sub query, solution is above, it is working now.
Here's an example on how to manage multiple result-rows:
function connect()
{
$db = mysql_connect("localhost","username","password") or die("your error msg");
mysql_select_db("database_name");
return $db;
}
$db = connect();
$query = "SELECT value1 FROM my_table";
$result = mysql_query($query, $db);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
// This one will loop through the data in your output//
$outputValue = $row['value1'];
}
For inserting data:
// Continued from the state above //
$query = "INSERT INTO table_name (column1) VALUES (value1)";
$result = mysql_query($query, $db) or die(mysql_error());
$_10day is a mysql result, not a value. You can't just put a result into a query string and expect it to work.
You need to get the result data first, eg;
while($row = mysql_fetch_assoc($_10day)) {
$10day = $row['AVG(close)'];
}
Then you can execute your insert query;
mysql_query ("INSERT INTO _$symbol (_10day) VALUES ('$10day')");
Hope this helps.

The max value in a column with php

I have a MySql table "MyTable" with the column "order"
order
-----
3
4
2
1
I want to get the highest number. The sql statement works well inside MySql:
SELECT MAX(order) FROM MyTable"
But I do not know how to use it with php and echo it? Something like:
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row[0];
If you don't provide an alias to a MySQL function it will be shown as you've written it:
$row = mysqli_fetch_array($result);
echo $row['MAX(order)'];
What you can do is write something like:
$result = mysqli_query($con, "SELECT MAX(order) as 'max' FROM MyTable");
$row = mysqli_fetch_array($result);
echo $row['max'];
Which is using an alias.
Hope this helps!
Alternatively you can use ORDER BY DESC and Limit result to 1 this way you can easily get the maximum of an column .
$result=$con->query("SELECT order FROM MyTable ORDER BY order DESC LIMIT 1");
$row=mysqli_fetch_array($result);
echo $row['order'];
Or using MAX
$result = mysqli_query($con, "SELECT MAX(order) FROM MyTable");
$row=mysqli_fetch_array($result);
echo $row[0];
This tutorial is directly from tizag, using the MySql Max function
MySQL Aggregate Functions - MAX()
// Make a MySQL Connection
$query = "SELECT type, MAX(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The most expensive ". $row['type']. " is $" .$row['MAX(price)'];
echo "<br />";
}
Here's my answer:
$host = "localhost";
$username = "your_username";
$password = "your_password";
$db_name = "your_db_name";
$connection = mysql_connect($host, $username, $password) or die ("Error:: [1]");
mysql_select_db($db_name, $connection) or die ("Error:: [2]");
$query = "SELECT `order` FROM `MyTable` order by `order` desc";
$res = mysql_query($query, $connection);
$row = mysql_fetch_array($res);
print $row[0];
With this query , you always have the highest value of the give column.

Categories