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.
Related
I want to send data to database, but if result = 1 status=plusone, result = 2 status=plustwo, etc..
It should work like that..
But no, it work like this: result = 2 status=plusone .
What did i missed? Help me..
I've tried this:
$item = '0';
$result = $item + $points;
and:
$result = $points + 0;
Here is rest (part of) code:
if($result = 1){
$Sql_Query ="INSERT INTO points SET unique_id = '$id', description = '$Description', points = '$points', status= 'plusone'";
if(mysqli_query($con,$Sql_Query)) {
echo 'Succcess!';
}
}elseif($result = 2){
$Sql_Query ="INSERT INTO points SET unique_id = '$id', description = ' $Description', points = '$points', status= 'plustwo'";
if(mysqli_query($con,$Sql_Query)) {
echo 'Succcess!';
}
}
= and == are different; = is for assignment, and == is to compare statement
I'm new to PHP, now I face some strange issue about updating the value.
From these codes
for($i=0; $i < $count; $i++){
$sql = ("UPDATE applicant_skill SET App_skill_performance_score = '".$s_score[$i]."', App_skill_knowledge_score = ".$k_score[$i]."' WHERE App_Data_ID ='".$a_id."' && Position_ID = '".$p_id."' && Skill_ID = '".$skill_id[$i]."' ");
$resultt = "";
if ($conn->query($sql) == TRUE) {
$resultt = "FINISH";
} else {
$resultt = "ERROR";
}
}
At first I use INSERT and it works fine. Now I change to UPDATE but it updates nothing (the field is already in database waiting for update).
I don't know where mistake is, please help.
Try
$sscrore = $s_score[$i];
$kscore = $k_score[$i];
$aid = $a_id;
$pid = $p_id;
$skillid = $skill_id[$i];
$sql = ("UPDATE applicant_skill SET App_skill_performance_score = '$sscrore', App_skill_knowledge_score = '$kscore' WHERE App_Data_ID ='$aid' AND Position_ID = '$pid' AND Skill_ID = '$skillid' ");
Basically, you are missing one ' before ".$k_score[$i]."'
use AND instead of &&
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';
}
Okay so I am new to PHP and attempting to make a script that takes all of the data from a mysql database I have of stock prices and then looks to see if there was an increase in the stock price during after hours trading (by comparing one day's close price with the next day's open price). I have set up a few scripts like this that work, but for some reason this script isn't copying the data into my sql database and I am completely stumped as to why it won't.When I set up echo statements throughout I discovered that my code is seemingly being executed everywhere but the data isn't transferring. Any help is greatly appreciated.
<?php
include("../includes/connect.php");
function masterLoop(){
$mainTickerFile = fopen("../tickerMaster.txt","r");
while (!feof($mainTickerFile)){
$companyTicker = fgets($mainTickerFile);
$companyTicker = trim($companyTicker);
$nextDayIncrease = 0;
$nextDayDecrease = 0;
$nextDayNoChange = 0;
$total = 0;
$overnight_change = 0;
$overnight_change_pct = 0;
$sumOfIncreases = 0;
$sumOfDecreases = 0;
$sql = "SELECT date, open, close, percent_change FROM $companyTicker";
$result = mysql_query($sql);
if($result){
while($row = mysql_fetch_array($result)){
$date = $row['date'];
$percent_change = $row['percent_change'];
$open = $row['open'];
$close = $row['close'];
$sql2 = "SELECT date, open, close, percent_change FROM $companyTicker WHERE date > '$date' ORDER BY date ASC LIMIT 1";
$result2 = mysql_query($sql2);
$numberOfRows = mysql_num_rows($result2);
if($numberOfRows==1){
$row2 = mysql_fetch_row($result2);
$tom_date= $row2[0];
$tom_open= $row2[1];
$tom_close= $row2[2];
$tom_percent_change= $row2[3];
if ($close == 0){
$close = $tom_open;
}
$overnight_change = $tom_open - $close;
$overnight_change_pct = ($overnight_change/$close)*100;
if($overnight_change_pct > 0){
$nextDayIncrease++;
$sumOfIncreases += $tom_percent_change;
$total++;
}else if($overnight_change_pct < 0){
$nextDayDecrease++;
$sumOfDecreases += $tom_percent_change;
$total++;
}else{
$nextDayNoChange++;
$total++;
}
}else if ($numberOfRows==0){
$total = 1;
$nextDayIncrease = 1;
$nextDayDecrease = 1;
}else{
echo "You have an error in analysis_c3";
}
}
}else{
echo "unable to select $companyTicker <br />";
}
$nextDayIncreasePercent = ($nextDayIncrease/$total) * 100;
$nextDayDecreasePercent = ($nextDayDecrease/$total) * 100;
$averageIncreasePercentage = $sumOfIncreases/$nextDayIncrease;
$averageDecreasePercentage = $sumOfDecreases/$nextDayDecrease;
insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage);
}
}
function insertIntoResultTable($companyTicker, $nextDayIncrease, $nextDayIncreasePercent, $averageIncreasePercentage, $nextDayDecrease, $nextDayDecreasePercent, $averageDecreasePercentage){
$buyValue = $nextDayIncreasePercent * $averageIncreasePercentage;
$sellValue = $nextDayDecreasePercent * $averageDecreasePercentage;
$trueValue = $buyValue + $sellValue;
$query="SELECT * FROM analysisOvernightGain5 WHERE ticker='$companyTicker' ";
$result=mysql_query($query);
$numberOfRows = mysql_num_rows($result);
if($numberOfRows==1){
$sql = "UPDATE analysisOvernightGain5 SET ticker='$companyTicker',daysInc='$nextDayIncrease',pctOfDaysInc='$nextDayIncreasePercent',avgIncPct='$averageIncreasePercentage',daysDec='$nextDayDecrease',pctOfDaysDec='$nextDayDecreasePercent',avgDecPct='$averageDecreasePercentage',buyValue='$buyValue',sellValue='$sellValue'trueValue='$trueValue' WHERE ticker='$companyTicker' ";
mysql_query($sql);
}else{
$sql="INSERT INTO analysisOvernightGain5 (ticker,daysInc,pctOfDaysInc,avgIncPct,daysDec,pctOfDaysDec,avgDecPct,buyValue,sellValue,trueValue) VALUES ('$companyTicker', '$nextDayIncrease', '$nextDayIncreasePercent', '$averageIncreasePercentage', '$nextDayDecrease', '$nextDayDecreasePercent', '$averageDecreasePercentage', '$buyValue', '$sellValue','$trueValue')";
mysql_query($sql);
}
}
masterLoop();
?>
you have missed , at ,sellValue='$sellValue'trueValue='$trueValue'
it should be ,sellValue='$sellValue',trueValue='$trueValue'
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.