I have calculated the average price of products by type in a table and gotten the results into my screen. How do I store them into a table as well. Here is the code I have. it works other than to store into a table.
function mostrarDatos ($resultado) {
if ($resultado !=NULL) {
echo "- Promedio de Categoria ".'Producto_Prioridad'." es:".$resultado['total_average']."<br/>";
}
else {
echo "<br/>No hay más datos!!! <br/>";
}
}
$link = mysqli_connect("db", "user", "pass");
mysqli_select_db($link, "db");
$promedio = mysqli_query($link, "SELECT AVG( Producto_Precio ) as total_average FROM`Natan_Productos` GROUP BY Producto_Prioridad");
while ($fila = mysqli_fetch_array($promedio)){ // loops 4 times and displays on screen. How to store into table as well
mostrarDatos($fila);
}
mysqli_free_result($promedio);
mysqli_close($link);
for results I get:
- Promedio de Categoria Producto_Prioridad es:150.0000 //Loop 1
- Promedio de Categoria Producto_Prioridad es:38.3333 //Loop 2
- Promedio de Categoria Producto_Prioridad es:30.0000 //Loop 3
- Promedio de Categoria Producto_Prioridad es:31.6667 //Loop 4
Thanks for the help.
I guess you are not familiar with php & mysql.
First, you should have a table for storing the result.Let's create a simple table if you do not have one.
create table result_for_total_average ( avg_info varchar(256) );
Then, modify your function like this.
function mostrarDatos ($resultado, $link) {
if ($resultado !=NULL) {
mysqli_query($link, "INSERT INTO result_for_total_average values("."- Promedio de Categoria ".'Producto_Prioridad'." es:".$resultado['total_average'].")");
}else {
echo "<br/>No hay más datos!!! <br/>";
}
}
$link = mysqli_connect("db", "user", "pass");
mysqli_select_db($link, "db");
$promedio = mysqli_query($link, "SELECT AVG( Producto_Precio ) as total_average FROM`Natan_Productos` GROUP BY Producto_Prioridad");
while ($fila = mysqli_fetch_array($promedio)){ // loops 4 times and displays on screen. How to store into table as well
mostrarDatos($fila);
}
mysqli_free_result($promedio);
mysqli_close($link);
The table I created is just simple enough to store the result, you can create your own one. If you do not know how to, here is a good start:http://www.w3schools.com/sql/default.asp.
If you want learn more about how php and mysql work together, you can reference to http://www.w3schools.com/php/php_mysql_intro.asp
Create a table for inserting your new products
id (auto increment) | name | country | number
while ($fila = mysqli_fetch_array($promedio))
{
$product = mostrarDatos($fila);
// Mysql Insert
}
You could use an INSERT INTO SELECT
statement, which looks something like so,
INSERT INTO <table-x> (<column-x>) SELECT <column-y> FROM <table-y>;
or in your case, something like so,
INSERT INTO Natan_Average_Productos (product)
SELECT CONCAT("- Promedio de Categoria Producto_Prioridad es:", AVG(Producto_Precio)) AS total_average
FROM Natan_Productos
GROUP BY Producto_Prioridad;