Is there any way I can avoid doing this (which is looping through directory data in a database, and then getting the same data for all it's children, and childrens children... ad infinitum:
$directories = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `level` = '1' AND `batch` = %s", $lastBatchID);
foreach ($directories as $dir) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir");
$size = intval($dirInfo[0]['size']) * 1024;
echo stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories2 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir, $lastBatchID);
foreach ($directories2 as $dir2) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir2");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories3 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir2, $lastBatchID);
foreach ($directories3 as $dir3) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir3");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories4 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir3, $lastBatchID);
foreach ($directories4 as $dir4) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir4");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories5 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir4, $lastBatchID);
foreach ($directories5 as $dir5) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir5");
$size = intval($dirInfo[0]['size']) * 1024;
echo "=>=>=>=>" . stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
}
}
}
}
}
Basically we are getting data for x number of levels of directories, and need a loop for each of the levels to display the data as follows:
C:\it\AD-Chris Integration -Current:49.70M
=>C:\it\AD-Chris Integration\AD-Chris2 -Current:49.69M
=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris -Current:5.22M
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Common -Current:599.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Department -Current:453.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Encrypt -Current:327.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Location -Current:387.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Manager -Current:1.36M
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\ScanForStaffID -Current:348.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\Title -Current:498.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\bin -Current:529.00K
=>=>=>C:\it\AD-Chris Integration\AD-Chris2\AD-Chris\obj -Current:439.00K
=>=>C:\it\AD-Chris Integration\AD-Chris2\_Deploy -Current:622.00K
I have a variable available which has the number of levels deep we need to go
function something($dir, $lastBatchID, $level = 0) {
$dirInfo = DB::query("SELECT `folder`, `size` FROM `data` WHERE `id` = $dir");
$size = intval($dirInfo[0]['size']) * 1024;
echo str_repeat('=>', $level);
echo stripslashes($dirInfo[0]['folder']) . " -Current:" . human_filesize($size) . "<br>";
$directories2 = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `parentID` = %s AND `batch` = %s", $dir, $lastBatchID);
if ($level > 5) return;
foreach ($directories2 as $dir2) {
something($dir2, $lastBatchID, $level + 1);
}
}
$directories = DB::queryOneColumn('id', "SELECT `id` FROM `data` WHERE `level` = '1' AND `batch` = %s", $lastBatchID);
foreach ($directories as $dir) {
something($dir, $lastBatchID);
}
Related
I have this code which is supposed to delete two image files from two diffrent folders at the same time. The issue is, only one image is deleted. the other is not. I have tried different methods but still the same issue.
Below is my code.
<?php
$colname_albumedit = "-1";
if (isset($_GET['arf'])) {
$colname_albumedit = $_GET['arf'];
}
$query_album = "SELECT * FROM galbum WHERE alID = '" . $colname_albumedit . "'";
$result_album = mysqli_query($connKcla, $query_album);
$row_album = mysqli_fetch_assoc($result_album);
$totalRows_album = mysqli_num_rows($result_album);
$query_album_images = "SELECT * FROM gimage WHERE alID = '" . $colname_albumedit . "'";
$result_album_images = mysqli_query($connKcla, $query_album_images);
$row_album_images = mysqli_fetch_assoc($result_album_images);
$totalRows_album_images = mysqli_num_rows($result_album_images);
if ((isset($_POST["form_del"])) && ($_POST["form_del"] == "adalbumdel")) {
$target = "../gallery/albums/";
$targett = "../gallery/images/";
$imID = $_GET['arf'];
$sql_query = "SELECT alImage FROM galbum WHERE alID = $imID";
$photoresult = mysqli_query($connKcla, $sql_query);
$row_album = mysqli_fetch_assoc($photoresult);
if (($row_album['alImage']) != 0) {
unlink($target . $row_album['alImage']);
}
$sql_queryy = "SELECT albumRef FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_assoc($photoresultt);
if (($row_album_images['albumRef']) != 0) {
unlink($targett . $row_album_images['albumRef']);
}
$query_del = "DELETE FROM galbum WHERE alID = $colname_albumedit";
$result_del = mysqli_query($connKcla, $query_del);
$queryy_del = "DELETE FROM gimage WHERE alID = $colname_albumedit";
$resultt_del = mysqli_query($connKcla, $queryy_del);
if ($result_del && $resultt_del) {
$updateGoTo = "confirm.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header("Location: " . $updateGoTo);
} else {
header("Location: error.php");
}
}
The table gImage looks like this:
CREATE TABLE IF NOT EXISTS gimage (
imID bigint(20) NOT NULL AUTO_INCREMENT,
imImage varchar(255) DEFAULT NULL,
albumRef bigint(20) DEFAULT NULL,
PRIMARY KEY (imID), KEY alID (albumRef)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
Think, just replace this code
$sql_queryy = "SELECT albumRef FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_assoc($photoresultt);
if (($row_album_images['albumRef']) != 0) {
unlink($targett . $row_album_images['albumRef']);
}
with this code.
$sql_queryy = "SELECT imImage FROM gimage WHERE albumRef = $imID";
$photoresultt = mysqli_query($connKcla, $sql_queryy);
$row_album_images = mysqli_fetch_all($photoresultt);
foreach ($row_album_images as $row) {
unlink($targett . $row[0]);
}
Recommendation
Rename your variable $imID cause it is in reality the albumId. As you can see in your code in the lines
$imID = $_GET['arf'];
$sql_query = "SELECT alImage FROM galbum WHERE alID = $imID";
I have created several functions to pull data from a MySQL database.
I have my main query that loops through each horse in a racecard and uses the functions to pull data on that horse. The code that uses the functions is below:
//note I'm using select * until I finish knowing what I need to pull//
$horses12 = mysqli_query($db, 'SELECT * FROM tom_cards');
while($todayhorse12 = mysqli_fetch_array($horses12)){
$horse = $todayhorse12['Horse'];
$distance = $todayhorse12['Distance'];
$trainer = $todayhorse12['Trainer'];
$jockey = $todayhorse12['Jockeys_Claim'];
$weight = $todayhorse12['Weight'];
$class = $todayhorse12['Class'];
//function calls go here e.g
echo $horse.horselargerace($horse,$db)."<br />";
}
The issue as every function calls my database and it either takes forever or connections time out. Below are the functions - can anyone figure out a way to cut down on the number of MySQL connections I need to make?
///////////////////////////////////////////////////////////////////////////////////////
//did the horse run in a large field of 12 or more horses and perform well recently?//
//////////////////////////////////////////////////////////////////////////////////////
function horselargerace($horse, $db)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Runners > 12 ORDER BY Date Limit 5');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$runners = 0;
if ((int) $todayhorse['Place'] < 5) {
$count = $count + 1;
}
}
return $count;
}
//////////////////////////////////////////////////////////////////
//is the horse moving up in class after a good finish or a win?//
////////////////////////////////////////////////////////////////
function horselastclass($horse, $db, $class)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$class2 = trim(str_replace("Class", "", $todayhorse['Class']));
$class = trim(str_replace("Class", "", $class));
if ($class2 == "") {
$class2 = $class;
}
if (trim($class) != "" or trim($class2) != "") {
//if a horse is being dropped in class this should be easier
if ((int) $class < (int) $class2) {
$count = $count + 1;
} elseif ((int) $class > (int) $class2) {
$count = $count - 1;
}
}
}
return $count;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//is the horse picking up or dropping weight today? //
// 114pds or under is ideal.horse drops 5pds or more from the last start i take that as a positive, if he picks up more than 5pds then i consider that a negative.//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function horselastweight($horse, $db, $weight)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$weight2 = preg_replace("/[^a-zA-Z]/", "", $weight);
$weight2 = substr($weight2, 0, 1);
if ($weight2 <> "") {
$weight = substr($weight, 0, strpos($weight, $weight2));
}
//get stone and convert to pounds
$total1 = (((int) substr($weight, 0, strpos($weight, "-"))) * 14) + (int) substr($weight, 1, strpos($weight, "-"));
$total2 = (((int) substr(str_replace(chr(194), "", $todayhorse['Weight']), 0, strpos(str_replace(chr(194), "", $todayhorse['Weight']), "-"))) * 14) + (int) substr(str_replace(chr(194), "", $todayhorse['Weight']), 1, strpos(str_replace(chr(194), "", $todayhorse['Weight']), "-"));
$weight = str_replace(chr(194), "", $todayhorse['Weight']) . "=" . $weight;
}
$total = (int) $total2 - (int) $total1;
if ((int) $total > 4) {
$count = $count + 1;
} elseif ((int) $total < -4) {
$count = $count - 1;
}
return $count;
}
//////////////////////////////////////////////////////////////////////////////
//did the horse have trouble in his/her last race? (comments broke slow ect)//
/////////////////////////////////////////////////////////////////////////////
function horsehavetrouble($horse, $db)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Place'] = "2" or $todayhorse['Place'] = "3" or $todayhorse['Place'] = "4" or $todayhorse['Place'] = "5") {
$targets = array(
"hampered",
"awkward",
"stumbled",
"slipped",
"jinked",
"fell",
"unseated"
);
foreach ($targets as $target) {
if (strstr(strtolower($todayhorse['Comments']), $target) !== false) {
$count = $count + 1;
}
}
}
}
return $count;
}
///////////////////////////////////////////////////////////////
//is the same jockey back on today after not winning in last?//
///////////////////////////////////////////////////////////////
function isjockeyonagainafterlosing($horse, $db, $jockey)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place != "1" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
$pop = array_pop(explode(' ', $todayhorse['Jockeys_Claim']));
if (trim(array_pop(explode(' ', $todayhorse['Jockeys_Claim']))) == trim(array_pop(explode(' ', trim($jockey))))) {
$count = $count + 1;
}
}
return $count;
}
//////////////////////////////////////////////////////
//has the jockey won previously on this same horse?//
////////////////////////////////////////////////////
function Hasjockeywonbeforeonhorse($horse, $db, $jockey)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place ="1" ORDER BY Date');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
//get todays jockey and check to see if it matches with prev ones
if (trim(array_pop(explode(' ', $todayhorse['Jockeys_Claim']))) <> trim(array_pop(explode(' ', trim($jockey))))) {
$count = $count + 1;
}
}
return $count;
}
////////////////////////////////////
//is the horse changing trainers?//
//////////////////////////////////
function horsechnagedtrainers($horse, $db, $trainer)
{
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
while ($todayhorse = mysqli_fetch_array($horses)) {
$count = 0;
//compare last trainer and current
if (trim(array_pop(explode(' ', $todayhorse['Trainer']))) <> trim(array_pop(explode(' ', trim($trainer))))) {
$count = $count + 1;
}
}
return $count;
}
///////////////////////////////////////////////
//has the horse won at high odds in the past?//
///////////////////////////////////////////////
function horsehighodds($horse, $db)
{
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "' . $horse . '" and Place ="1" ORDER BY Date Limit 1');
while ($todayhorse = mysqli_fetch_array($horses)) {
$fraction = str_replace("F", "", $todayhorse['Odds']);
$fraction = str_replace("J", "", $fraction);
$fraction = explode("/", $fraction);
if ($fraction[1] != 0) {
$fraction = ($fraction[0] / $fraction[1]);
}
$fraction = (int) $fraction;
if (in_array((int) $fraction, range(2, 6))) {
$count = $count + 1;
}
}
return $count;
}
///////////////////////////////////////////////////////
//was the horse between 2-1 & 6-1 odds in last start?//
///////////////////////////////////////////////////////
function horsebetween2and6($horse, $db)
{
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 1');
$count = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
//convert the odds to decimal
$fraction = str_replace("F", "", $todayhorse['Odds']);
$fraction = str_replace("J", "", $fraction);
$fraction = explode("/", $fraction);
if ($fraction[1] != 0) {
$fraction = ($fraction[0] / $fraction[1]);
}
$fraction = (int) $fraction;
if ((int) $fraction <= 2 and (int) $fraction >= 6) {
$count = $count + 1;
}
if (in_array((int) $fraction, range(2, 6))) {
$count = $count + 1;
}
return $count;
}
}
//////////////////////////////////////////////////////
//was this horse a beaten favorite in last 3 starts?//
//////////////////////////////////////////////////////
function horsebeatenfav($horse, $db)
{
$count = 0;
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "' . $horse . '" ORDER BY Date Limit 3');
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Place'] <> "1" and strpos($todayhorse['Odds'], 'F') !== false) {
$count = $count + 1;
}
}
return $count;
}
////////////////////////////////////////////////
//How many starts has the horse had this year?//
////////////////////////////////////////////////
function startswithin12months($horse, $db)
{
$startdate = date('Y-m-d', strtotime('-1 year'));
$enddate = date('Y-m-d');
$horses = mysqli_query($db, 'SELECT Date FROM horsesrp where Horse = "' . $horse . '" and Date >= "' . $startdate . '" AND Date <= "' . $enddate . '" ORDER BY Date');
return $horses->num_rows;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Is the horse changing distances today? - find out if the horse has ever won at this distance - if not -1point//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function hashorsechangedistance($horse, $distance, $db)
{
//select all distances this horse has run
$horses = mysqli_query($db, 'SELECT Distance FROM horsesrp where Horse = "' . $horse . '" ORDER BY Date');
//count the times its run at this distance
$distancecount = 0;
while ($todayhorse = mysqli_fetch_array($horses)) {
if ($todayhorse['Distance'] == $distance) {
$distancecount = $distancecount + 1;
}
}
//if distance is greater then 0 its ran at this distance before
return $distancecount;
}
/////////////////////////////////////////////////////////
//How long has the horse been off (time between races)?//
/////////////////////////////////////////////////////////
function horselastrace($horse, $db)
{
//select horse last run
$sql = 'SELECT `Date` FROM `horsesrp` where `Horse` = "' . $horse . '" ORDER BY Date limit 1';
$horses = mysqli_query($db, $sql);
while ($todayhorse = mysqli_fetch_array($horses)) {
$dStart = new DateTime($todayhorse['Date']);
$dEnd = new DateTime(date('Y-m-d'));
$dDiff = $dStart->diff($dEnd);
return $dDiff->days;
}
}
Queries grouped together will be as follows:
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 1');
$sql = 'SELECT `Date` FROM `horsesrp` where `Horse` = "'.$horse.'" ORDER BY Date limit 1';
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place != "1" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place ="1" ORDER BY Date');
$horses = mysqli_query($db, 'SELECT Odds FROM `horsesrp` WHERE `horse` = "'.$horse.'" and Place ="1" ORDER BY Date Limit 1');
$horses = mysqli_query($db, 'SELECT * FROM `horsesrp` WHERE `horse` = "'.$horse.'" ORDER BY Date Limit 3');
$horses = mysqli_query($db, 'SELECT Date FROM horsesrp where Horse = "'.$horse.'" and Date >= "'.$startdate.'" AND Date <= "'.$enddate.'" ORDER BY Date');
$horses = mysqli_query($db, 'SELECT Distance FROM horsesrp where Horse = "'.$horse.'"');
Table structure:
Field
Type
Null
Key
Default
Extra
ID
int(255)
NO
PRI
NULL
auto_increment
ParentID
int(255)
NO
NULL
Date
date
NO
NULL
Track
varchar(100)
YES
NULL
Runners
varchar(50)
YES
NULL
Going
varchar(50)
YES
NULL
Distance
varchar(50)
YES
NULL
Class
varchar(50)
YES
NULL
Place
varchar(10)
YES
NULL
Losing_Dist
varchar(50)
YES
NULL
Stall
varchar(250)
YES
NULL
Horse
varchar(50)
YES
NULL
Weight
varchar(50)
YES
NULL
Trainer
varchar(50)
YES
NULL
Odds
varchar(50)
YES
NULL
Oddsmovement
varchar(250)
NO
NULL
Jockeys_Claim
varchar(50)
YES
NULL
Comments
varchar(250)
YES
NULL
Race_Name
varchar(250)
YES
NULL
Timetaken
varchar(255)
NO
NULL
OR
varchar(6)
NO
NULL
Do you have index on field Horse in table horsesrp? Specified queries should be processed fast, even with large dataset. You can do this as follows:
ALTER TABLE horsesrp ADD INDEX Horse (Horse);
More on MySQL Indexes:
http://dev.mysql.com/doc/refman/5.5/en/mysql-indexes.html
How do MySQL indexes work?
OK I know I probably need to use a str_replace and I have tried $thequery = str_replace("'", "''", $thequery); but it didn't work. Please don't ding me on the code...I didn't write it. Each week we get a txt file done like a CSV with all our course offerings and we copy and paste it into a web page with the following code and it gets posted to an MSSQL table...however sometimes we have a course name with an ' and then it doesn't load and we have to manually remove the '. I need to escape the ' and can use some help.
if ($_POST) {
if(isset($_POST['semester'])) {
# Table name to upload to
$tablename = $_POST['semester'];
} else {
die("No table to use");
}
# Parsing of the text
$thequery = $_POST['sql'];
$thequery = str_replace("\"", "'", $thequery);
$thequery = str_replace(".00", "", $thequery);
$thequery = str_replace(".50", "", $thequery);
$thequery = str_replace("'Brien", " Brien", $thequery);
$thequery = str_replace("'Shaughnessy", " Shaughnessy", $thequery);
$thequery = str_replace("--", "10-01-01", $thequery);
$thequery = str_replace("WEB", "Online", $thequery);
$squery = explode("\n", $thequery);
$names = array();
$equery = array();
$i = 0;
foreach($squery as $newquery) {
$a = split('[*]', $newquery);
$final = substr($a[0], 0, -2);
$newid = $a[1];
$names[$i] = $newid;
$equery[$i] = $final;
$i++;
}
$scount = 0;
# Easiest way to redo the course list was to drop the table and re-insert it with the new values
mssql_query("DROP TABLE [dbo].[$tablename]") or die(mysql_error());
mssql_query("CREATE TABLE [dbo].[$tablename] (division CHAR(4) NULL, cid CHAR(11) NULL, cname CHAR(45) NULL, credits TINYINT NULL, days CHAR(7) NULL, day_M TINYINT NULL, day_T TINYINT NULL, day_W TINYINT NULL, day_R TINYINT NULL, day_F TINYINT NULL, day_S TINYINT NULL, sdate DATETIME NULL, edate DATETIME NULL, stime DATETIME NULL, etime DATETIME NULL, duration CHAR(5) NULL, building CHAR(3) NULL, room CHAR(4) NULL, method CHAR(12) NULL, instructor CHAR(40) NULL, secsyn INT NULL)") or die(mysql_error());
# Inserts the courses
while ($scount < count($equery)) {
mssql_query("INSERT INTO [dbo].[$tablename] (division, cid, cname, credits, days, day_M, day_T, day_W, day_R, day_F, day_S, sdate, edate, stime, etime, duration, building, room, method, instructor, secsyn) VALUES ($equery[$scount])") or die(mysql_error());
print($equery[$scount] . " has been entered.<br>");
$scount++;
}
# Quick hack to update the "Last Updated" with the current date
$date = date("M j Y g:iA");
mssql_query("UPDATE courses SET updated='$date' WHERE id='ABED140'") or die(mysql_error());
$nq = mssql_query("SELECT * FROM [dbo].[$tablename] WHERE method='Online'") or die(mysql_error());
$tnum = 0;
print("<br /><br />");
# Sets courses to Hybrids if they have a 'H' in the course ID
while($tnum < mssql_num_rows($nq)) {
$tcourse = mssql_result($nq,$tnum,"cid");
$ccode = explode(" ",$tcourse);
if(isset($ccode[1])) {
if (strpos($ccode[1], 'H') !== false) {
mssql_query("UPDATE [dbo].[$tablename] SET method='Hybrid' WHERE cid='$tcourse'") or die(mysql_error());
print("Updated " . $tcourse . " to be a Hybrid course.<br />");
}
}
$tnum++;
}
# Special cases for certain classes that need to be set as a Hybrid
# Simply add $sq[NEXT NUMBER] = "COURSE ID"; and it will set it to a Hybrid
$sq = array();
$sq[0] = "BIOL101 WH";
$sq[1] = "BIOL140 WH";
foreach ($sq as $nq) {
if(mssql_num_rows(mssql_query("SELECT * FROM [dbo].[$tablename] WHERE cid='$nq'")) > 0) {
mssql_query("UPDATE [dbo].[$tablename] SET method='Hybrid' WHERE cid='$nq'") or die(mysql_error());
print("Updated " . $nq . " to be a Hybrid course.<br />");
}
}
# Checking to make sure the online classes have a special_online table link
$cq = mssql_query("SELECT * FROM [dbo].[$tablename] WHERE method='Online' OR method='Hybrid'");
$cn = 0;
while($cn < mssql_num_rows($cq)) {
$ccid = mssql_result($cq,$cn,"cid");
$ncq = mssql_query("SELECT * FROM [dbo].[special_online] WHERE cid='$ccid'");
if(mssql_num_rows($ncq) == 0) {
mssql_query("INSERT INTO [dbo].[special_online] (cid,url) VALUES ('$ccid','http://dacc.blackboard.com')") or die(mysql_error());
print("Updated " . $ccid . " to have a online course link.<br />");
}
$cn++;
}
} else {
# Prints our form that shows when page is first loaded
print("<form action='' method='post'><select name='semester'>
<option value='2011SP'>2011SP</optoin>
<option value='2011SU'>2011SU</option>
<option value='2011FA'>2011FA</option>
<option value='2011FA'>2011WI</option>
<option value='2012SP'>2012SP</option>
<option value='2012SU'>2012SU</option>
<option value='2012FA'>2012FA</option>
<option value='2013SP'>2013SP</option>
<option value='2013SU'>2013SU</option>
<option value='2013FA'>2013FA</option>
<option value='2013WI'>2013WI</option>
<option value='2014SP'>2014SP</option>
<option value='2014SU'>2014SU</option>
<option value='2014FA'>2014FA</option>
</select><br><br>Insert the statement:<br><textarea name='sql' rows='10' cols='100'></textarea><br><input type='submit' value='Submit'></form>");
}
Try to replace ' with \ before you put that in your database:
Change this line:
$thequery = str_replace("\"", "'", $thequery);
to:
$thequery = str_replace("'", "\\", $thequery);
DEMO
I need to select 4 random ids from the table, but problem is that they are sometimes duplicated how to avoid that? I have tried to use DISTINCT but with no results here is the code.As for CMS I am using opencart.
<h1>similar products</h1>
<?php
$id = $this->customer->getCustomerGroupId();
$cur_jur = $this->db->query("SELECT `value` FROM `" . DB_PREFIX . "currency` WHERE currency_id = '1'");
$cur_fiz = $this->db->query("SELECT `value` FROM `" . DB_PREFIX . "currency` WHERE currency_id = '3'");
$max_symb = 25;
$fee_id = $product_id;
$product_sql_test_fee = $this->db->query("SELECT `category_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `product_id`='".$fee_id."' ORDER BY RAND() LIMIT 0,10");
$feed_id = $product_sql_test_fee->row['category_id'];
$i=1;
$imax = 5;
$products_id = '';
while ($i < $imax)
{
$product_fee = $this->db->query("SELECT DISTINCT `product_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `category_id`='".$feed_id."' AND NOT `product_id` = '".$products_id."' GROUP BY `product_id` ORDER BY RAND() LIMIT 0,10");
if(isset($product_fee->row['product_id']))
{
$pr_id[$i] = $product_fee->row['product_id'];
}
$pr_id_[$i] = $this->model_catalog_product->getProduct($pr_id[$i]);
$products_id .= $pr_id[$i].',';
$product_duplicate = explode(',',$products_id);
if ($product_duplicate[$i] == $pr_id[$i])
{
}
//if ($product_duplicate[$i] == $pr_id[$i]){ //echo 'Duplicate';
//continue;} else {
//foreach ($product_duplicate as $id) {
//if ($id == $pr_id[$i]) continue;
//}
//$price_plus = $pr_id_[$i]['price'] + ($pr_id_[$i]['price'] * 0.20);
//$price_minus = $pr_id_[$i]['price'] - ($pr_id_[$i]['price'] * 0.20);
//$price_of_product = (int)$price / $cur_fiz->row['value'];
//if ($price_of_product < $price_plus && $price_of_product > $price_minus) {
//echo $pr_id[$i].'||'.$price_minus.'||'.$price_plus.'||'.$pr_id_[$i]['price'].'||'.$price_of_product.'<br/>';
//}
$price_plus = $pr_id_[$i]['price'] + ($pr_id_[$i]['price'] * 0.30);
$price_minus = $pr_id_[$i]['price'] - ($pr_id_[$i]['price'] * 0.30);
$price_of_product = (int)$price / $cur_fiz->row['value'];
if ($price_of_product < $price_plus && $price_of_product > $price_minus )
{
}
}
?>
You have to use group by category_id problem will be resolved.
SELECT DISTINCT `product_id` FROM `" . DB_PREFIX . "product_to_category` WHERE `category_id`='".$feed_id."' AND NOT `product_id` = '".$products_id."' GROUP BY `category_id`
I am making a script to create a CSV file to pull data out of ze DB. When I run the script it comes back with unexpected T_Variable on line 173 # '$body'. I have checked it a few times and also looked up other incidents with this issue. Perhaps I am overlooking (lack of sleep). Any help would be greatly appreciated!
#!/usr/bin/php
<?php
mysql_connect('localhost', '******', '********');
mysql_select_db('*****');
$id_query = mysql_query("SELECT `id` FROM `leads` WHERE `status` = 'Passed' AND `campaign_id` = '22d0cf4f-0f81-28b1-d8dc-4f06bd1d8ee'");
$id = mysql_fetch_row($id_query);
echo $id[0];
$first_name_query = mysql_query("SELECT `first_name`
FROM `leads`
WHERE `id` = '$id[0]'");
$first_name = mysql_fetch_row($first_name_query);
$url_first_name = $first_name[0];
echo $url_first_name;
$last_name_query = mysql_query("SELECT `last_name`
FROM `leads`
WHERE `id` = '$id[0]'");
$last_name = mysql_fetch_row($last_name_query);
$url_last_name = $last_name[0];
echo $url_last_name;
$phone_home_query = mysql_query("SELECT `phone_home`
FROM `leads`
WHERE `id` = '$id[0]'");
$phone_home = mysql_fetch_row($phone_home_query);
$url_phone_home = $phone_home[0];
echo $url_phone_home;
$primary_address_street_query = mysql_query("SELECT `primary_address_street`
FROM `leads`
WHERE `id` = '$id[0]'");
$primary_address_street = mysql_fetch_row($primary_address_street_query);
$url_primary_address_street = $primary_address_street[0];
echo $url_primary_address_street;
$primary_address_city_query = mysql_query("SELECT `primary_address_city`
FROM `leads`
WHERE `id` = '$id[0]'");
$primary_address_city = mysql_fetch_row($primary_address_city_query);
$url_primary_address_city = $primary_address_city[0];
echo $url_primary_address_city;
$primary_address_state_query = mysql_query("SELECT `primary_address_state`
FROM `leads`
WHERE `id` = '$id[0]'");
$primary_address_state = mysql_fetch_row($primary_address_state_query);
$url_primary_address_state = $primary_address_state[0];
echo $url_primary_address_state;
$primary_address_postalcode_query = mysql_query("SELECT `primary_address_postalcode`
FROM `leads`
WHERE `id` = '$id[0]'");
$primary_address_postalcode = mysql_fetch_row($primary_address_postalcode_query);
$url_primary_address_postalcode = $primary_address_postalcode[0];
echo $url_primary_address_postalcode;
$dateofbirth_c_query = mysql_query("SELECT `dateofbirth_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$dateofbirth_c = mysql_fetch_row($dateofbirth_c_query);
$url_dateofbirth_c = $dateofbirth_c[0];
echo $url_dateofbirth_c;
$gender_c_query = mysql_query("SELECT `gender_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$gender_c = mysql_fetch_row($gender_c_query);
$g2 = substr($gender,0,1);
$url_gender = $g2[0];
echo $url_gender_c;
$testblood_c_query = mysql_query("SELECT `testblood_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$testblood_c = mysql_fetch_row($testblood_c_query);
$b2 = substr($testblood_c,0,1);
$url_testblood_c = $b2[0];
echo $url_testblood_c;
$physicianlastname_c_query = mysql_query("SELECT `physicianlastname_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physicianlastname_c = mysql_fetch_row($physicianlastname_c_query);
$url_physicianlastname_c = $physicianlastname_c[0];
echo $url_physicianlastname_c;
$physicianfirstname_c_query = mysql_query("SELECT `physicianfirstname_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physicianfirstname_c = mysql_fetch_row($physicianfirstname_c_query);
$url_physicianfirstname_c = $physicianfirstname_c[0];
echo $url_physicianfirstname_c;
$physiciancity_c_query = mysql_query("SELECT `physiciancity_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physiciancity_c = mysql_fetch_row($physiciancity_c_query);
$url_physiciancity_c = $physiciancity_c[0];
echo $url_physiciancity_c;
$physicianstate_c_query = mysql_query("SELECT `physicianstate_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physicianstate_c = mysql_fetch_row($physicianstate_c_query);
$url_physicianstate_c = $physicianstate_c[0];
echo $url_physicianstate_c;
$physicianphone_c_query = mysql_query("SELECT `physicianphone_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physicianphone_c = mysql_fetch_row($physicianphone_c_query);
$url_physicianphone_c = $physicianphone_c[0];
echo $url_physicianphone_c;
$physicianfax_c_query = mysql_query("SELECT `physicianfax_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physicianfax_c = mysql_fetch_row($physicianfax_c_query);
$url_physicianfax_c = $physicianfax_c[0];
echo $url_physicianfax_c;
$physiciannpi_c_query = mysql_query("SELECT `physiciannpi_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$physiciannpi_c = mysql_fetch_row($physiciannpi_c_query);
$url_physiciannpi_c = $physiciannpi_c[0];
echo $url_physiciannpi_c;
$primaryinsurance_c_query = mysql_query("SELECT `primaryinsurance_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$primaryinsurance_c = mysql_fetch_row($primaryinsurance_c_query);
$url_primaryinsurance_c = $primaryinsurance_c[0];
echo $url_primaryinsurance_c;
$policynumber_c_query = mysql_query("SELECT `policynumber_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$policynumber_c = mysql_fetch_row($policynumber_c_query);
$url_policynumber_c = $policynumber_c[0];
echo $url_policynumber_c;
$vendorid_c_query = mysql_query("SELECT `vendorid_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$vendorid_c = mysql_fetch_row($vendorid_c_query);
$url_vendorid_c = $vendorid_c[0];
echo $url_vendorid_c;
$groupnumber_c_query = mysql_query("SELECT `groupnumber_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$groupnumber_c = mysql_fetch_row($groupnumber_c_query);
$url_groupnumber_c = $groupnumber_c[0];
echo $url_groupnumber_c;
$pcn_number_c_query = mysql_query("SELECT `pcn_number_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$pcn_number_c = mysql_fetch_row($pcn_number_c_query);
$url_pcn_number_c = $pcn_number_c[0];
echo $url_pcn_number_c;
$bin_number_c_query = mysql_query("SELECT `bin_number_c`
FROM `leads_cstm`
WHERE `id_c` = '$id[0]'");
$bin_number_c = mysql_fetch_row($bin_number_c_query);
$url_bin_number_c = $bin_number_c[0];
echo $url_bin_number_c;
if ($first_name != ''){
$date = date("m-d-y");
$time = time();
$blank = "";
$timestamp = 'A03-'.$date.'-'.$time;
$header = 'BeneficiaryFirstName,BeneficiaryLastName,BeneficiaryAddress1,BeneficiaryAddress2,BeneficiaryCity,BeneficiaryState,BeneficiaryZipCode,BeneficiaryPhone,BeneficiaryDOB,EMail,VendorCustomerID,DoctorNPI,DoctorName,DoctorAddress1,DoctorAddress2,DoctorCity,DoctorState,DoctorZipCode,DoctorPhone,DoctorFax,InsuranceType,InsuranceID,GroupID,BIN,PCN,InsuranceCompanyName,DailyTest,BeneficiaryGender,BestTimeToCall,SourceIP,CurrentMethod,LeadSource,Dependent,Password,ProductTypeID,Incentive';
$body = $url_first_name.','.$url_last_name.','.$url_primary_address_street.','.$blank.','.$url_primary_address_city.','.$url_primary_address_state.','.$url_primary_address_postalcode.','.$url_phone_home.','.$url_dateofbirth_c.','.$blank.','.$url_phone_home.','.$url_physiciannpi_c.','.$blank.','.$blank.','.$blank.','.$url_physiciancity_c.','.$url_physicianstate_c.','.$blank.','$url_physicianphone_c.','.$url_physicianfax_c.','.$url_primaryinsurance_c.','.$url_policynumber_c.','.$url_groupnumber_c.','.$url_bin_number_c.','.$url_pcn_number_c.','.$url_primaryinsurance_c.','.$url_testblood_c.','.$url_gender_c.','.$blank.','.$blank.','.$blank.','.$blank.','.$blank.','.$blank.','.$blank;
$filename = '/home/orsini/Ol-'.$timestamp.'.csv';
$handle = fopen($filename,'w');
fwrite($handle,$header."\n");
fwrite($handle,$body."\n");
fclose($handle);
mysql_query("UPDATE leads SET `status` = 'sold_orsini' WHERE `id` = '$id[0]'");
}
?>
You forgot one dot in your line with $body = $url_first_name at the very end:
,'$url_physicianphone_c.'
Why not use an IDE??
Here is your proper line with $body. You just missed a ..
$body = $url_first_name
.','
.$url_last_name
.','
.$url_primary_address_street
.','
.$blank
.','
.$url_primary_address_city
.','
.$url_primary_address_state.','.$url_primary_address_postalcode.','
.$url_phone_home.','.$url_dateofbirth_c.','.$blank.','.$url_phone_home.','.$url_physiciannpi_c.','
.$blank.','.$blank.','.$blank.','.$url_physiciancity_c.','.$url_physicianstate_c.','
.$blank.','.$url_physicianphone_c . ',' . $url_physicianfax_c
.',' . $url_primaryinsurance_c . ','
.$url_policynumber_c . ',' . $url_groupnumber_c . ',' . $url_bin_number_c . ',' . $url_pcn_number_c . ',' . $url_primaryinsurance_c . ',' . $url_testblood_c
. ',' . $url_gender_c . ',' . $blank . ',' . $blank . ',' . $blank . ',' . $blank . ',' . $blank . ',' . $blank . ',' . $blank;
Found it $url_physicianphone_c. should be .$url_physicianphone_c. Now it has .$url and works.
You can improve things if you consolidated all these queries into just a few. Use table joins to improve this. The DB will be faster at searching and sorting than your PHP.
That said you should also use the PHP CSV functions. Check it out here: http://us.php.net/manual/en/function.fputcsv.php