Creating a MySQL query using a loop - php

I'm developing a system that is used for booking resources per hour. For example booking a conference room by the hour or whatever. I've pretty much got all the functionality working but some things are far from perfect and there's one function that I've got that's bugging me. It's booking a resource for an entire week. My code for it is below but any help on making it more efficient would be greatly appreciated.
Thanks!
Steve
function bookweek($week) {
global $deskid, $date, $time, $member_id, $bookingTimes, $day0, $day1, $day2, $day3, $day4, $day5, $day6, $day7, $day8, $day9, $day10, $day11, $day12, $day13;
dbconnect();
switch($week) {
case 1:
$dupecheck = mysql_query("SELECT * FROM booked where deskid='$deskid' AND date>='$day0' AND date <'$day7'");
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$daynumber=$j;
$testing = "day".$daynumber;
$daytotal= $$testing;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql="INSERT INTO booked (date, time, deskid, member_id) VALUES ('$daytotal', '$i', '$deskid', '$member_id')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}
break;
case 2:
$dupecheck = mysql_query("SELECT * FROM booked where deskid='$deskid' AND date > '$day6'");
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$daynumber=$j+7;
$testing = "day".$daynumber;
$daytotal= $$testing;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql="INSERT INTO booked (date, time, deskid, member_id) VALUES ('$daytotal', '$i', '$deskid', '$member_id')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}
break;
}
}

That will be hard to maintain if used for any case the whole sql block.
Make it more efficient.
function bookweek($week) {
global $deskid, $date, $time, $member_id, $bookingTimes, $day0, $day1, $day2, $day3, $day4, $day5, $day6, $day7, $day8, $day9, $day10, $day11, $day12, $day13;
$queryP = "SELECT * FROM booked where deskid='".$deskid."' AND date>";
dbconnect();
switch($week) {
case 1:
$dupecheck = mysql_query($queryP."='".$day0."' AND date <'".$day7."'");
break;
case 2:
$dupecheck = mysql_query($queryP."'".$day6."'");
break;
}
if (mysql_num_rows($dupecheck) == 0)
[...]
And give mysqli a try
Now the code is more clear and it is immediately apparent that things can be improved.
$queryP = "SELECT * FROM booked where deskid='".$deskid."' AND date>";
dbconnect();
switch($week) {
case 1:
$queryP .= "='".$day0."' AND date <'".$day7."'";
break;
case 2:
$queryP .= "'".$day6."'";
break;
}
$dupecheck = mysql_query($queryP);
if (mysql_num_rows($dupecheck) == 0)
[...]
Let's come to the loop.
In order to better test on errors. I would change only the inner loop.
if (mysql_num_rows($dupecheck) == 0)
{
for($j = 0; $j< 7; $j++)
{
$testing = "day".$j;
$daytotal= $$testing;
$sql = "INSERT INTO booked (date, time, deskid, member_id) VALUES ";
$sqlTest = $sql;
for($i = 1; $i < count($bookingTimes)+1; $i++)
{
$sql .= "('".$daytotal."', '".$i."', '".$deskid."', '".$member_id."'),";
}
if ($sql == $sqlTest) {
// nothing to be done or die
} else {
$sql = rtrim($sql,",");
result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
}

I think that if you use prepared statements you will save much MySQL resources.

Related

how can foreach mysql result?

I have 2 Columns in mysql. valami2 and playerID in table players_extra.
I will the following:
give 3000 coppers for the first row in valami2, then 2500 coppers for the second(then each row -500 coppers until the 5th place)....after the 5th place give 500 until the 10th place. for the CORRECT payerID.
$aseco->console('>> Updating `hetimostfin` counts for all Players...');
$hetimostfin = array();
$line = 0;
$coppers = 3000;
$query = "
SELECT
`playerID`,
COUNT(`valami2`) AS `Count`
FROM `players_extra`
GROUP BY `playerID`;
";
$res2 = mysql_query($query);
if ($res2) {
if (mysql_num_rows($res2) > 0) {
while ($row = mysql_fetch_object($res2)) {
$hetimostfin[$row->playerID] = $row->Count;
}
foreach ($hetimostfin as $id => $count) {
$res2 = mysql_query("
UPDATE `players_extra`
SET `valami2` =(`valami2`+'".$coppers."')
WHERE `playerID` = ". $id ."
");
$line ++;
$coppers=($coppers-500);
if ($line >= 6) {
$coppers=500;
}
if ($line == 10){
break;
}
}
}
}
Try PDO. It's a much better and safer way of interacting with databases for PHP. http://php.net/manual/en/pdo.connections.php
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$hetimostfin = array();
$coppers = 3000;
$line = 0;
$query = <<<SQL
SELECT
playerID,
COUNT(valami2) AS `count`
FROM players_extra
GROUP BY playerID;
SQL;
foreach($dbh->query($query, PDO::FETCH_ASSOC) as $row) {
$hetimostfin[[$row['playerID']] = $row['count'];
// execute update statement
$line++;
}

multiple row saving to DB table

I have to save more than one row of data into database table.
I wrote this code for that. But when i run this code, two rows will be saved into two rows of db table, but every other row is same as the last row data.
i.e. that is the last row data is overwriting every other row data.
$values = array();
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
You aren't resetting your values array inside the loop so values[0] and values[1] will always have the first to values.
if (isset($_POST['sub_save'])) {
$row_count = $_POST['rowcount'];
while ($row_count > 0) {
$values = array();
for ($r = 1; $r <= 2; $r++) {
$val = $_POST['txt'.$row_count.$r];
$values[] = $val;
}
$row_count = $row_count - 1;
$sql = "insert into timesheet_entry (name, address) values ('$values[0]', '$values[1]')";
if (mysql_query($sql)) {
echo "inserted";
} else {
echo "fail";
}
}
}
On a sidenote I would recommend looking into the PDO extension and parameterised queries as mysql_ is deprecated and the above code is vulnerable to SQL injection
You are mixing mysql and mysqli:
$conn = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db("dbname");
if (mysqli_query($sql)) {
echo "inserted";
} else {
echo "fail";
}

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 not transferring to mysql database

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'

php code doesn't enter loop (mysqli)

I try to make a diagram with RGraph(JS). I have a user counter on my site. And now I want to make a user-statistic with this diagram.
However I created a list which should be used for every query (made a form to choose month and year).
My problem is that the code doesnt enter the loop to create the new values (Day and Count).
Any idea?
Here the code:
$days = 0;
$day_value = array();
//check months which have 30 days
if (in_array($month, array(4,6,9,11))) {
$days = 30;
}
//leapyear?
if ($month == 2) {
if ($year%4 == 0) {
$days = 29;
} else {
$days = 28;
}
}
//Count users for each day
for ($i=1; $i<=$days; $i++) {
$sql = "SELECT
Anzahl
FROM
Counter
WHERE
YEAR(Datum) = '".$year."' AND
MONTH(Datum) = '".$month."' AND
DAYOFMONTH(Datum) = '".$i."'";
if (!$result = $db->query($sql)) {
return $db->error;
}
$row = $result->fetch_assoc();
$day_value[$i] = (int)$row['Anzahl'];
}
//delete list for new month/year
$sql = "DELETE
FROM
Statistics
";
if (!$result = $db->query($sql)) {
return $db->error;
}
//Create list with values for each day
for ($j=1; $j<=$days; $j++) {
$sql = "INSERT INTO
Statistics(Day,Count)
VALUES
(?, ?)";
$stmt = $db->prepare($sql);
if (!$stmt) {
return $db->error;
}
$stmt->bind_param('ii', $j, $day_value[$j]);
if (!$stmt->execute()) {
return $stmt->error;
}
$stmt->close();
}
$days is set to 0, it only changes if $months is 2,4,6,9,11 so for every other value of $month $days will be 0 and not enter the for loop.
if (in_array($month, array(4,6,9,11))) {
//code
}
elseif ($month == 2) {
//code
}
else{
//code
}

Categories