PHP not transferring to mysql database - php

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'

Related

database query, compare each two rows but getting only first two rows

Hi i am querying my db so that i can compare every two rows. ex 1 and 2, then 2 and 3, then 3 and 4. and so on and so forth. but it only compares the first two rows. any ideas? here is my code:
$result = mysql_query("SELECT *FROM attendance ORDER BY pid ASC") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// $response["nominees"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$prev_sid = $row["sid"];
$prev_pid = $row["pid"];
$row2 = mysql_fetch_array($result);
if($row2["pid"] == $prev_pid){
if(($row2["sid"] - $prev_sid) == 1){
$attended_elec = mysql_query("SELECT pid FROM election_attendance where election_id = '$election_id'");
if(mysql_num_rows($attended_elec) > 0){
$not_officer = mysql_query("SELECT usertype FROM users WHERE pid = '$prev_pid'");
if(mysql_result($not_officer, 0) == "member"){
// echo "PID" . $prev_pid;
// $nominee["pid"] = $row2["pid"];
$user_details = mysql_query("SELECT *FROM users WHERE pid = '$prev_pid'");
if(mysql_num_rows($user_details) > 0){
$response["nominees"] = array();
while ($row3 = mysql_fetch_array($user_details)) {
$nominee = array();
$nominee["pid"] = $row3["pid"];
$nominee["firstname"] = $row3["firstname"];
$nominee["lastname"] = $row3["lastname"];
$nominee["gender"] = $row3["gender"];
$nominee["contact"] = $row3["contact"];
$nominee["email"] = $row3["email"];
$nominee["address"] = $row3["address"];
$nominee["institution"] = $row3["institution"];
$nominee["points"] = $row3["points"];
$nominee["usertype"] = $row3["usertype"];
// push single product into final response array
array_push($response["nominees"], $nominee);
}
}
}
}
}
}
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "There is no candidate yet from the records.";
// echo no users JSON
echo json_encode($response);
}
thanks in advance, have a nice day
Theres a problem right at the while(), you're fetching the 1st row, and is correct.
Then, inside it you fetch the 2nd, which is what you intend, but when the iteration is repeating, the while will fetch the 3rd, and the inner the 4th, so you lost there the comparisson between 2nd and 3rd.
// fetch data from DB
$results = "...";
if (mysql_num_rows($result) < 1)
{
// no products found tell your users
return;
}
// lets make some variables to walk through the list
$previous = mysql_fetch_array($results);
$actual = null;
// and now lets walk through the list
while($actual = mysql_fetch_array($results))
{
// execute your logic here
// than at the end move the actual row to become the previous
$previous = $actual;
}
NOTICE you shouldn't use mysql_ * methods they're are deprecated. you can use the brother mysqli_ * or PDO
I would do something like this? But there is almost certainly a less resource intensive way to do it.
$x = 0;
$y = 1;
$total = mysql_num_rows(mysql_query("SELECT * FROM `the_place`");
while ($x < $total AND $y < total){
$query1 = "SELECT * FROM `the_place` LIMIT $x,1";
$query2 = "SELECT * FROM `the_place` LIMIT $y,1";
$row1 = mysql_fetch_array(mysql_query($query1);
$row2 = mysql_fetch_array(mysql_query($query2);
// Do comparison here
if ($row1 == $row2){
// etc
}
$x = $x++;
$y = $y++;
}

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;
}
}
}

$i not incrementing in while loop

Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.

Return multiple rows with mysqli

I am in the process of learning mysqli and I am trying to query a databases and return multiple rows. I understand that a loop has to be used to return multiple rows but I have no idea how I would implement this into my code. Some help in doing this would be greatly appreciated.
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['hour'];
$minute = $row ['minute'];
$journeyid = $row ['journeyid'];
try this code
<?php
$con= mysqli_connect('localhost', 'root', '', 'your data base name');
$query2 = mysqli_query($con,"SELECT * FROM journeys where id=$id");
$count = mysqli_num_rows($query2);
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;
} else {
while ( $row = mysqli_fetch_assoc($query2) ) {
$from = $row ['origin'];
$to = $row ['destination'];
$date = $row ['date'];
$hour = $row ['our'];
$minute = $row ['minute'];
$journeyid =$row ['journeyid'];
echo $from.'<br>';
}
}
have a look at this line echo $from; this will display what ever you have in the origin column in your database, if you want to display destination, use this as well echo $to;
means what ever you want to display do it like this echo $variableName; it will display the result;
before you display the result it will only store it, but will not display it,
have a look i change your this line of code as well
its your code
if ($count == 0) {
$journeys = 'You have no future journeys.';
echo $journeys;// i added this line
i added one line, because what you are saying here that if $count is equal to zero, than $journeys='you have no future journeys'; but you are not using echo you have to use echo to display the result.
if you still have some confusion ask again, and try to google as well
$query2 = mysqli_query($con,"SELECT * FROM journeys WHERE id = $id");
$row = mysql_fetch_array($query2);
$count = count($row);
if(intval($count)>0)
{
for($i = 0; $i<$count; $i++)
{
$from[$i] = $row[$i]['origin'];
-------------------------------
----------------------
}
}

INSERT INTO not populating database table

I have a script that checks the submitgame table and if both approve1 and approve 2 are not blank it inserts data into clanstats. There is no mysql_error it simply redirects to the header without inserting anything into the clanstats table, so I have no idea what is going on. Below is the code.
<?php
include("user.php");
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id'") or die(mysql_error());
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}
else {
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$playerclan', '$points', '$win')");
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES ('$opponentclan', '$points2', '$win2')");
echo mysql_error($query);
}
else {
header("location:../approvegames.php");
}
mysql_close($con);
header("location:../approvegames.php");
?>
<?php
//first off are you connecting, ill presume so
include("user.php");
//sql injection!!!
$id = mysql_real_escape_string($_GET['id']);
$result = mysql_query("SELECT * FROM submitgame WHERE id='$id' limit 1") or die(mysql_error());
//you were missing this
$row=mysql_fetch_array($result);
$playerclan = $row['playerclan'];
$opponentclan = $row['opponentclan'];
$win = $row['win'];
$approve1 = $row['approve1'];
$approve2 = $row['approve2'];
if($win == "won") {
$win = 1;
$points = 2;
$win2 = 0;
$points2 = 1;
}else{
$win = 0;
$points = 1;
$win2 = 1;
$points2 = 2;
}
if($approve1 != "" && $approve2 != "") {
//you can have multiple inserts
$query=mysql_query("INSERT INTO clanstats (clan, points, wins) VALUES
('$playerclan', '$points', '$win'),
('$opponentclan', '$points2', '$win2')");
header("location:../approvegames.php");
//adding die after the header will make sure nothing else gets executed
die();
}else{
header("location:../approvegames.php");
die();
}
//no need to kill the connection as it will close when the script exits
?>
I think you are missing a line. Perhaps something like:
$row = mysql_fetch_row($result)

Categories