optimize query: get all votes from user's item - php

i did it my way because i'm very bad getting results from two tables...
Basically, first i get all the id items that correspond to the user, and then i calculate the ratings of each item.
But, there is two different types of object item, so i do this 2 times: show you:
function votos_usuario($id){
// $previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
// $r_previo = mysql_query($previa);
// $ids_p = '0, ';
// while($items_previos = mysql_fetch_array($r_previo)){
// $ids_p .= $items_previos['id'].", ";
// //echo "ids pregunta usuario: ".$items_previos['id']."<br>";
// }
// $ids = substr($ids_p,0,-2);
// //echo $ids;
//
// $consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
// //echo $consulta;
//
// $resultado = mysql_query($consulta);
// $votos_preguntas = 0;
// while($voto = mysql_fetch_array($resultado)){
// $votos_preguntas = $votos_preguntas + $voto['valor'];
// }
$votos_preguntas= 0;
$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
As you can si this is two much.. O(n^2)
Feel like thinking?
thanks!

You can do this for both:
$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
If votos_pregunta and votos_rectas have the same structure, I would only have it as one table with a newly added type column that could be either rectas or preguntas. Then you need to only do one statement for $total.

Related

Dynamic INSERT with full variables in PHP

I would appreciate it if someone can guide me with the following problem, I need to do a INSERT into a MySQL database with variables, here is my code example:
$valor = "$valor.", ".$total;
$table = $dta.$year;
$insert = "ano, id, idas".$valor2.", total";
$value = $year.", ".$id.", ".$idas.$tit2.", ".$monto3;
$sql = "INSERT INTO `$table` (`$insert`) VALUES (`$value`)";
The general idea is that the amount of columns are not known until the program is run as it is all dynamic.
The following code is used to build the table as needed, which works fine:
while(($row = mysql_fetch_array($result)) !== FALSE)
{
$columna=$row['pn'];
$valor= $valor." pt".$columna." VARCHAR(50),";
$valor2= $valor2.", pt".$columna;
$gestion = '3';
$table = "sumag".$gestion.$year;
}
$valor= "ano VARCHAR(4), id VARCHAR(4), idas VARCHAR(13), ".$valor." "."total VARCHAR(10)";
For this reason the first code also has to be dynamic..
I really need help on this, I am not a programmer and I have built this from what I have learnt, so most probally my tecnique is pretty bad, if anyone can help it would be great..
Thank You
You have declared the column name as idas VARCHAR(13), in table but the insert element declared with some additional values idas".$valor2.". Check this one instance right now..
Here is the full code:
<?php
$gestion = 3;
$data = "SELECT * FROM progdesc where gestion = '$gestion'" or die("¡Error No existe ese departamento!");
$result = mysql_query($data) or die("¡Error No existe ese dep!");
while(($row = mysql_fetch_array($result)) !== FALSE)
{
$columna=$row['pn'];
$valor= $valor." pt".$columna." VARCHAR(50),";
$valor2= $valor2.", pt".$columna;
$gestion = '3';
$table = "sumag".$gestion.$year;
}
$valor= "ano VARCHAR(4), id VARCHAR(4), idas VARCHAR(13), ".$valor." "."total VARCHAR(10)";
#echo $table." - ".$valor;
mysql_query("CREATE TABLE `".$table."`(".$valor.")") or die(mysql_error());
//------------------------------------Insert data -----------------------------------------//
//-1--------Get Asig N°--------//
$data1 = "SELECT * FROM asigna" or die("¡Error No existe ese departamento!");
$result1 = mysql_query($data1) or die("¡Error1!");
while(($row = mysql_fetch_array($result1)) !== FALSE)
{
$id=$row['id'];
$idas=$row['idas'];
$sid=$row['sid'];
$tit2 = NULL;
$monto3 = 0;
//-2-------Get Gestion and DEPFINAL---------------------//
$data2 = "SELECT * FROM progdesc WHERE gestion = '$gestion' and ano = '$year' " or die("¡Error No existe ese departamento!");
$result2 = mysql_query($data2) or die("¡Error2!");
while(($row2 = mysql_fetch_array($result2)) !== FALSE)
{
$dep=$row2['departamento'];
$titulo=$row2['titulo'];
$depf = $dep."final";
$pn = $row2['pn'];
$sidb = $row2['sid'];
#$monto3 = 0;
#echo $pn;
//-3-------Get Program N° and create chain------------//
$data3 = "SELECT * FROM $depf WHERE ano = '$year' and idas = '$idas' and gestion = '$gestion'and programa = '$pn' " or die("¡Error No existe ese departamento!");
$result3 = mysql_query($data3) or die("¡Error3!");
while(($row3 = mysql_fetch_array($result3)) !== FALSE)
{
$monto=$row3['monto'];
if (!($idas2 == $idas and $monto == 0)){
$tit2 = $tit2.", ".$monto;
}elseif ($monto == 0){
$tit2 = $tit2.", 0";
} else {
$cero = 0;
$pn2 = 0;
If (!($monto == 0)){
for ($i = 0; $i < $pn2; $i++) {
$cero = $cero.", 0";
}
$tit2 = $tit2.", ".$cero.", ".$monto;
}
}
$idas2 = $idas;
$ln = $ln + 1;
$monto2 = $monto;
$monto3 = $monto3 + $monto;
}
}
$insert = "ano, id, idas".$valor2.", total";
$value = $year.", ".$id.", ".$idas.$tit2.", ".$monto3;
$sql = "INSERT INTO `$table` (`$insert`) VALUES (`$value`)";
myquery($sql); }
I just want to make clear that I am not a programmer and I know my code is not up to standard in any way, I was forced to complete this task just because I kinda know programming, this is why I am asking for help, if there is anther way to complete the task, great and thanks fr all have responded so far, I apreciate your patience.

delete not working properly in while loop

here i am trying to delete from detail table here is one problem with my code if detail table have three records than only delete one record from detail table.and also it does not effect other two records in stock table..
Only one first record this code work properly after that it does not work in for delete query from detail table and not effected in stock table...
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0) {
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId, colorId,
totalkg, purchaseDetailId, partyId
FROM purchasedetail
JOIN purchasemaster ON
purchaseMaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster);
while($purRow = mysql_fetch_array($selectMasterRes)) {
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes)) {
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes) {
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes){
$deleteMst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$deleteMstRes = mysql_query($deleteMst) or die(mysql_error());
if(!$deleteMstRes) {
echo "Purchase Master Delete Fail";
} else {
header("Location:purdetail.php");
exit();
}
}
}
}
}
?>
Here is my updated code with perfect code working
<?php
include("include/config.inc.php");
$purchaseMasterId = isset($_REQUEST['purchaseMasterId']) ? $_REQUEST['purchaseMasterId'] : 0;
if($purchaseMasterId > 0)
{
$k = 0;
$selectMaster = "SELECT purchasedetail.purchaseMasterId,colorId,totalkg,purchaseDetailId,partyId
FROM purchasedetail
JOIN purchasemaster ON purchasemaster.purchaseMasterId = purchasedetail.purchaseMasterId
WHERE purchasedetail.purchaseMasterId = ".$_REQUEST['purchaseMasterId'];
$selectMasterRes = mysql_query($selectMaster) or die(mysql_error());
while($purRow = mysql_fetch_array($selectMasterRes))
{
$purchaseDetailId = $purRow['purchaseDetailId'];
$purchaseMasterId = $purRow['purchaseMasterId'];
$colorId = $purRow['colorId'];
$totalkg = $purRow['totalkg'];
$partyId = $purRow['partyId'];
$select = "SELECT qty
FROM stock
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$selectRes = mysql_query($select);
if($stockRow = mysql_fetch_array($selectRes))
{
$current = $stockRow['qty'];
}
$updateStock = "UPDATE stock
SET qty = ".$current." - ".$totalkg."
WHERE partyId = ".$partyId."
AND colorId = ".$colorId;
$updateStockRes = mysql_query($updateStock) or die(mysql_error());
if($updateStockRes)
{
$deleteDt = "DELETE FROM purchasedetail
WHERE purchaseDetailId = ".$purchaseDetailId;
$deleteRes = mysql_query($deleteDt);
if($deleteRes)
{
$selectid = "SELECT purchaseDetailId
FROM purchasedetail
WHERE purchaseMasterId = ".$purchaseMasterId;
$selectidRes = mysql_query($selectid);
if(mysql_affected_rows() == 0)
{
$mst = "DELETE FROM purchasemaster
WHERE purchaseMasterId = ".$purchaseMasterId;
$mstRes = mysql_query($mst) or die(mysql_error());;
if($mstRes)
{
header("Location:purdetail.php");
exit();
}
else
{
}
}
}
}
}
}
?>

DELETE SQL operation with PHP

I have problem with SQL DELETE in PHP language. I don't know where is the problem about delete sql operation.
Could you help me, please?
The code is:
$query = mysqli_query($connessione, "SELECT * FROM (SELECT date, time, temperature FROM streamcopy WHERE moteid = '".$sensor."' AND CONCAT(DATE, ' ',TIME) BETWEEN '".$i."' AND '".$f."' ORDER BY date DESC, time DESC) AS tab ORDER BY date, time");
$n = 0;
$m = 0;
while($row = mysqli_fetch_array($query)){
if($n == 0){
$num = $row['temperature']; //OK
$n = $n+1;
}
else{
$temp[$m] = $row; //OK
if(abs($num - $temp[$m]['temperature'])<0.5){ //OK
$queryFIXED = mysqli_query($connessione, "DELETE FROM streamcopy WHERE moteid = '".$sensor."' AND temperature = '".$temp[$m]['temperature']."' AND date = '".$temp[$m]['date']."' AND time = '".$temp[$m]['time']."')"); /* elimina dati di temperatura k vicini */
$n = $n+1;
$m = $m+1;
}
else{
$num = $temp[$m]['temperature'];
$n = $n+1;
$m = $m+1;
}
}
}

PHP, using Joomla, algorithm, networking if else,

Hi, I have a question, when i ever insert this code
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the if statement does not work anymore
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
but when i remove the
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the statement works perfectly ...
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}
This is the code
public function entryuni($newsponsorid = null, $lev = 2, $fpv = 0)
{
$db = & JFactory::getDBO();
$query = "SELECT upline,fslot FROM `table` where userid = '$newsponsorid' ";
$db->setQuery($query);
$items = $db->loadObject();
$items = (!empty($items)) ? $items : array();
$queryreach = mysql_query("SELECT * FROM incentives_table WHERE userid = '$newsponsorid' ");
$fetchreach = mysql_fetch_array($queryreach);
$pointsreach=$fetchreach['pointsreach'];
$tempunilevel=$fetchreach['temp_unilevel'];
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}

display array of items from DB php/MySQL

I am unsure how to display the items field. I want to display two tables of data; one that has all the items from a user and one with all the items to teh user. All I've been able to output is the item_id's(I pasted the html below). How to get all the item info from these ids, which is in the item table, and populate the HTML?
trans table
item table
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$t</td>
<td>$u</td></tr>";
}
HTML DISPLAY
Try this!
<?php
$from = 1;
$sql = $db->prepare("SELECT * FROM test WHERE from_id = :id");
$sql->bindValue(':id', $from);
$sql->execute();
while($row = $sql->fetch())
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$items = array();
foreach($itemIDs as $ID){
$sqlItem = $db->prepare("SELECT itemname FROM itemtable WHERE itemid = :itemid");
$sqlItem->bindValue(':itemid', $ID);
$sqlItem->execute();
$itemname ='';
while($rowItems = $sqlItem->fetch())
{
$itemname .=$rowItems['itemname'];
}
$items[$t] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$t]</td> <td>$u</td></tr>";
}
below is my code for testing,
<?php
$from = 1;
$sql = mysqli_query($db,"SELECT * FROM test WHERE from_id = '$from'");
while($row = mysqli_fetch_array($sql))
{
$t =$row['items'];
$u =$row['to_id'];
$itemIDs = #explode(",", $t);
$itemname ='';
foreach($itemIDs as $ID){
$sqlItem = mysqli_query($db, "SELECT itemname FROM itemtable WHERE item_id = '$ID'");
while($rowItems = mysqli_fetch_array($sqlItem))
{
$itemname .= $rowItems['itemname'].', ';
}
$items[$u] = $itemname;
}
$trans .= "<tr><th>Items</th><th>To</th><th>Status</th></tr><tr><td>$items[$u]</td> <td>$u</td></tr>";
}
echo "<table>".$trans."</table>";
?>
Note : change my queries with ur need
in ur while loop
while($row = $sql->fetch())
{
$items_array = array();
$items_array = explode(",",$row["items"]);
foreach($items_array as $key => $value)
{
//modify ur query according to ur need
$query3 = "SELECT item_name
FROM item_table
WHERE item_id =".$value." ";
$result3 = mysql_query($query3);
$row3 = mysql_fetch_assoc($result3);
$item_name .= $row3['subcategory_name'].", ";
}
}
now ur array will contains item_id,
use foreach loop in ur while loop and get info of Item from item table with item_id from expolode function
Within while you will have to fire new query that will get the information of items.
For eg :
"SELECT * FROM item_info_table WHERE id IN (id1,id2, id3)"
It will return you the item information corresponding to the id's.
The data is not normalized. Get it to normalize and you'll have a much better and cleaner solution.

Categories