Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

deleting images from folder

$
0
0

I'm trying to delete images from a folder if they don't exist in a table
This is what I have so far, but it deletes ALL of the images

Getting this warning as well

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home1/americans/public_html/stampfair.com/users/aimage_test.php on line 16

Because it is deleting ALL of the images, I'm guessing the db query result is failing is failing

Note that if I run the query alone, it returns the expected result

$link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");

$like = scandir('sfbuyer');     // IMAGE FOLDER
$query = "SELECT substr(value,42) FROM ppbv79_listings_media WHERE value like '%stampfair.com/users/russromei/%'"; // GETS THE FILE NAME

foreach ($like as $thisFile) {
$rs = mysqli_query($link,$query);
if (!mysqli_num_rows($rs)) {    // I KNOW THIS PART IS WRONG SHOULD BE SOMETHING LIKE if($thisFile != $like -- DOESN'T WORK
if($thisFile != "." and $thisFile != ".."){  // OR SHOULD BE HERE -- CAN'T GET IT TO ECHO VALUES SO WORKING BLIND
unlink ('sfbuyer/' . $thisFile);

}

}
}


Text string to array

$
0
0

Hey guys

how can i use php to turn a string like this:

 

“A, B#2, C#2, D#3, E”

 

Into an array like this:

 

Array

(

[1] => A

[2] => B

[3] => B

[4] => C

[5] => C

[6] => D

[7] => D

[8] => D

[9]=> E

)

 

I can get the letter and count into an array like this with the help of regex:

Array

(

[A] => 1

[B] => 2

 [C] => 2

 [D] => 3

 [D]=> 1

)

But I have no idea how I would get the result I desire – any help with this part would be greatly appreciated

How would you check image size and valid image format from multi image upload?

$
0
0

I have a script here that lets you upload and submit multiple images.  It works. But there are couple things i would like to add.

 

1. Have 2 mb limit for each image upload. Give an error if any of the image is over 2 mb.

2. Check if the uploaded images are valid types (jpeg, jpg, gift, and png).

 

Here is the script.

$get_username = 'myusername';
$get_email    = 'smith@myemail.com';

// we'll begin by assigning the To address and message subject
$to		=  "johndoe@myemail.com";
$subject	= "Subject message here....";

// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($get_username)."<".stripslashes($get_email).">";

// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
   "Content-Type: multipart/mixed;\r\n" .
   " boundary=\"{$mime_boundary}\"";

// here, we'll start the message body.
// this is the text that will be displayed
// in the e-mail
$message = "message text here...";

// next, we'll build the invisible portion of the message body
// note that we insert two dashes in front of the MIME boundary
// when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
   "--{$mime_boundary}\n" .
   "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
   "Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";

// now we'll process our uploaded files
foreach($_FILES as $userfile){
   // store the file information to variables for easier access
   $tmp_name = $userfile['tmp_name'];
   $type 		= $userfile['type'];
   $name 		= $userfile['name'];
   $size 		= $userfile['size'];

   // if the upload succeded, the file will exist
   if(file_exists($tmp_name)){

      // check to make sure that it is an uploaded file and not a system file
      if(is_uploaded_file($tmp_name)){

         // open the file for a binary read
         $file = fopen($tmp_name,'rb');

         // read the file content into a variable
         $data = fread($file,filesize($tmp_name));

         // close the file
         fclose($file);

         // now we encode it and split it into acceptable length lines
         $data = chunk_split(base64_encode($data));
      }

      // now we'll insert a boundary to indicate we're starting the attachment
      // we have to specify the content type, file name, and disposition as
      // an attachment, then add the file content.
      // NOTE: we don't set another boundary to indicate that the end of the
      // file has been reached here. we only want one boundary between each file
      // we'll add the final one after the loop finishes.
      $message .= "--{$mime_boundary}\n" .
         "Content-Type: {$type};\n" .
         " name=\"{$name}\"\n" .
         "Content-Disposition: attachment;\n" .
         " filename=\"{$fileatt_name}\"\n" .
         "Content-Transfer-Encoding: base64\n\n" .
      $data . "\n\n";
   }
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if(@mail($to, $subject, $message, $headers)) {
   echo 'sent';
} else {
  echo 'There was a problem. Please try again.';
}

One more thing. I notice that some of the images that i take from online(e.g. google images) won't upload, even though they are normal types like jpeg, gift, png. Do you know why that might happen? Are those images somehow encrypted or something?

Need to know how to set ad listings to expire 30 days in php mysql? PHP

$
0
0

I need to know how to set ad listings to expire 30 days in php mysql?
i know i have to ad some kind of feids in the myql table of listings

here is my php code to the page where it displays the for sale listings and catagories

</> <div class="orageBGfg" style="padding:2px 0px 2px 20px;">
<b>Category</b> : <? echo "$category";?>
<?
$query = "SELECT COUNT(*) FROM forsale_content WHERE category='$category' AND status='online'";
$numentries = mysql_query($query) or die("Select Failed!");
$numentry = mysql_fetch_array($numentries);
?>
</div>

  <b class="orageBG">
  <b class="orageBG5"></b>
  <b class="orageBG4"></b>
  <b class="orageBG3"></b>
  <b class="orageBG2"><b></b></b>
  <b class="orageBG1"><b></b></b></b>
</div>

<div id="title1">
Click on title to view description
</div>


<?
$sql = "SELECT * FROM forsale_content WHERE category='$category' AND status='online' ORDER BY id DESC";
$result = mysql_query($sql);
while ($record = mysql_fetch_object($result)) {

$question = nl2br($record->description);
$answer = nl2br($record->answer);
?>

<div id="list">
<a href="?q=detail&id=<? echo"$record->id";?>"><? echo "$record->title"; ?><?php if($record->price != "") { ?>
               - $<? echo number_format($record->price);?>
<?php } ?></a>
 <span>(<? echo "$record->city"; ?>) (<? echo "$record->postdate";?>)</span>

</div>

<?
}
?></>

here is the mysql table for the listing content

</>CREATE TABLE IF NOT EXISTS `forsale_content` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `postdate` date DEFAULT NULL,
  `posttime` varchar(10) DEFAULT NULL,
  `name` varchar(250) DEFAULT NULL,
  `phone` varchar(250) DEFAULT NULL,
  `address` varchar(250) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
  `country` varchar(250) DEFAULT NULL,
  `email` varchar(250) DEFAULT NULL,
  `website` varchar(250) DEFAULT NULL,
  `title` varchar(250) DEFAULT NULL,
  `price` varchar(250) DEFAULT NULL,
  `description` text,
  `category` varchar(250) DEFAULT NULL,
  `photo` varchar(250) DEFAULT NULL,
  `status` varchar(250) DEFAULT NULL,
  `password` varchar(25) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=46 ;</>

any help how to make this script s listing exprie after 30 or 60 or 90 days would be great thanks sorry for the bad code had to updat some of it to work with php 5.3 and up

Need help in making a php app connect to cleardb in heroku

$
0
0

I have recently decided to move to heroku from openshift, now i'm having a problem of not able to connect to cleardb mysql DB from heroku. need all of your help in this. Here is my php db config file. kindly let me know where im going wrong.

$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
  $server = $url["host"];
  $username = $url["user"];
  $password = $url["pass"];
  $db = substr($url["path"],1);
  $host= "mysql:host=$server;dbname=$db";
  var_dump($host);
try {
    $conn=new PDO($host , $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);} catch (PDOException $exc) {
    echo $exc->getMessage();
}
var_dump($conn);
echo "<br>";
var_dump($exc);
include 'classes.inc.php';
echo "<br>".$db."<br>";
$project= new projecteg($conn);

the output of $conn gives this

object(PDO)#1 (0) { }
NULL

and i dont know how to enable the error output in heroku too.

Left joins not being implemented correctly?

$
0
0

Hi,

 

Here is my SQL, its build with a loop, and looks correct to what I think it should be. I believe the output "$data" below should only be 4 records.. though its a lot more, and some data is duplicated and shown twice in the array.

 

Lot of stuff removed for simplicity.

SELECT usr.usr_login, app.app_name, acs.acs_read, acs.acs_add, acs.acs_edit, acs.acs_delete, acs.acs_admin FROM acs
LEFT JOIN usr
ON usr.ID = usr.ID
LEFT JOIN app
ON app.ID = app.ID

if it matters here's the code that generated the statement above from an array.

 
<?php

  // =====================================================================================================
  // preperation
  // =====================================================================================================
      foreach($fldarray as $fld){

          // get readable names and stick em into an array
          $nm[] = $fld['human'];

          // Field name, and joins (if the join is using the option table)
          if($fld['opt'] == 1 and ($fld['opt_table'] == "" or $fld['opt_field'] == "")){
            $jn[] = array('table' => "opt", 'field' => "opt_value");
            $fd[] = "opt.opt_value";

          // Field name, and joins (if the join is using a table other than options)
          }elseif($fld['opt'] == 1 and ($fld['opt_table'] <> "" and $fld['opt_field'] <> "")){
            $jn[] = array('table' => $fld['opt_table'], 'field' => $fld['opt_field']);
            $fd[] = $fld['opt_table'].".".$fld['opt_field'];

          // a field directly written no foreign keys..
          }else{
            $fd[] = $ap.".".$fld['fieldname'];
          }

          $sa[] = array('human' => $fld['human'], 'field' => $fld['fieldname'], 'opt_table' => $fld['opt_table'], 'opt_field' => $fld['opt_field']);

      }
  // =====================================================================================================
  // Start building the SQL
  // =====================================================================================================
      $sql = "SELECT ".implode(", ", $fd)." FROM ".$ap;
  // =====================================================================================================
  // Add the joins if any..
  // =====================================================================================================
      if (isset($jn)){
        foreach($jn as $j){
          $sql .= " LEFT JOIN ".$j['table']." ON ".$j['table'].".ID = ".$j['table'].".ID";
        }
      }
  // =====================================================================================================
      $stmt = $db->query($sql);
      $data = $stmt->fetchAll();
      echo $sql;
      echo "<pre>";
      print_r($data);
      echo "</pre>";
  // =====================================================================================================

?>
 

 

Tables

acs
ID  | acs_usr  | acs_app  | acs_read  | acs_add  | acs_edit  | acs_delete  | acs_admin
========================================================================================
1   | 1        | 1        | 1         | 1        | 1         | 1           | 1
1   | 1        | 1        | 1         | 0        | 1         | 1           | 0



app
ID | app_name
=============
1  | Applications
2  | Users


usr
ID | login
=============
1  | joe
2  | fred
3  | carlie
4  | lisa

outputs this array..

Array
(
    [0] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [1] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [2] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [3] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [4] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [5] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [6] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [7] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Applications
            [1] => Applications
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [8] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [9] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [10] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [11] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [12] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [13] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [14] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [15] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Users
            [1] => Users
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [16] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [17] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [18] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [19] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [20] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [21] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [22] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [23] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Permissions
            [1] => Permissions
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [24] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [25] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [26] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [27] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [28] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [29] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [30] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [31] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Benchmark
            [1] => Benchmark
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [32] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [33] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [34] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [35] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [36] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [37] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [38] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [39] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => News
            [1] => News
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [40] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [41] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [42] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [43] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [44] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [45] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [46] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [47] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Passwords
            [1] => Passwords
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [48] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [49] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [50] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [51] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [52] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [53] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [54] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [55] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Fields
            [1] => Fields
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [56] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [57] => Array
        (
            [usr_login] => Joe
            [0] => Joe
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [58] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [59] => Array
        (
            [usr_login] => fred
            [0] => fred
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [60] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [61] => Array
        (
            [usr_login] => carlie
            [0] => carlie
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

    [62] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 1
            [3] => 1
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 1
            [6] => 1
        )

    [63] => Array
        (
            [usr_login] => lisa
            [0] => lisa
            [app_name] => Settings
            [1] => Settings
            [acs_read] => 1
            [2] => 1
            [acs_add] => 0
            [3] => 0
            [acs_edit] => 1
            [4] => 1
            [acs_delete] => 1
            [5] => 1
            [acs_admin] => 0
            [6] => 0
        )

)

How to access a multiarray with PHP.

$
0
0

This is php programming..
I have tried just about every variation i can think of.. The goal is to be able to pull each value..
Then of course once i know what i need to pull the values i can put it in a loop to get them all.
Any assistance offered will be greatly appreciated.

print "<pre>";
print_r($myarray); // multiple triple array..
print "<pre>";

Array
(
    [DATA] => Array
        (
            [0] => Array
                (
                    [CurrentPrice] => 135000.00
                    [MLSNumber] => 857252
                    [Matrix_Unique_ID] => 8971579
                    [StreetName] => DENVER
                )

            [1] => Array
                (
                    [CurrentPrice] => 135000.00
                    [MLSNumber] => 857251
                    [Matrix_Unique_ID] => 8971581
                    [StreetName] => DENVER
                )

            [2] => Array
(
[CurrentPrice] => 135000.00
[MLSNumber] => 857253
[Matrix_Unique_ID] => 8971583
[StreetName] => DENVER
)

)

echo [0]['MLSNumber'];

echo [0][0]['MLSNumber'];

echo $myarray['MLSNumber'];

echo $myarray[0]['MLSNumber'];

echo [0][0]['MLSNumber'];

The above list is some of the attempts i have used to grab the values but negative results.

Two lists for one query...

$
0
0

I guess the 'easiest' question, is can there be two "while" loops with a query?  I've looked that up and haven't really found a definite answer.  

 

 

I'm not looking for code to be written yet, just a push in a certain direction.  Here is what I'm looking for:

 

I'm separately wanting player names and if there are any events players play in.  Games are not treated as events, so not every row deals with an event.  Most will be games, especially this time of year.   Right now I'm adding a row or two each game about individual players.  The last "event" was in October.  The next "event" won't be until April.  In the spring and summer, there could be as many as 30-40 rows for a single event.     

 

 

So I want two lists on this one page view:

 

The most recent events information is posted on.

 

 

The most recent players information is posted on.  

 

 

The screenshot below is the current list, grouped by player name, listed alphabetically.  Above it, I'd like to have from the same data table a list of the most recent events.  

 

Is it just easier to do it with a separate query?  I might be complicating this, but I was once told on here not to query the same table on the same file.  

 

Screen Shot 2017-12-27 at 8.50.50 AM.png

 

 


Taking 3 days off the input date of the user

$
0
0

Hi, 
 
Can someone point me in the right direction on how to do this 
 
I have a form (I have condensed it down to stop complicating things)

<input type="text" name="regid"/>
<input type="text" name="controlno"/>
<input type="text" name="hoverdate"/>
<button>My Submit Button</button>

The php function 

public function Addnew($regid, $controlno, $hoverdate)
    {
        try {
            $query = $db->prepare("INSERT INTO addnew(regid, controlno, hoverdate)
            VALUES (:regid,:controlno,:hoverdate)");
            $query->bindParam("regid", $regid, PDO::PARAM_STR);
            $query->bindParam("controlno", $chassis, PDO::PARAM_STR);
            $query->bindParam("hoverdate", $hoverdate, PDO::PARAM_STR);
	    $query->execute();
            return $db->lastInsertId();
        } catch (PDOException $e) {
            exit($e->getMessage());
        }
    }

And form data

if (!empty($_POST['btnAddNew'])) {
    if ($_POST['regid'] == "") {
        $add_error_message = 'Registration ID is required!';
    } else if ($_POST['controlno'] == "") {
        $add_error_message = 'A control number is required!';
	} else if ($_POST['hoverdate'] == "") {
        $add_error_message = 'When is the product being handed over';
    } else if ($app->isReg($_POST['regid'])) {
        $add_error_message = 'That Registration ID is already being processed!';
    } else {
   $user_id = $app->Addnew($_POST['regid'], $_POST['controlno'], $_POST['hoverdate']);

What I am trying to do is insert a 'pickingdate' into the database when the user submits the form

The date has to be 3 days prior to the "hoverdate" 

 

I am not sure where to start on this one and been scratching my head for ages trying to think of a solution but cannot for the life of me get my head round it...Any pointers would be much appreciated

 

Thanks in advance for any help

Allowed memory size of 134217728 bytes exhausted

$
0
0

Hi all

I am having problems with a script that uploads photo and adds watermarks to them.

 

Whenever I try and upload a photo I get the following error

Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 24576 bytes) in /home/sites/4a/1/13cb47e429/public_html/control/photos/processProduct.php on line 163

Line 163 is

 

 $image = imagecreatefromstring(file_get_contents($photo));

 

Let me know if you need the entire function for this and I will add it, but not sure what is wrong with the script, I have never seen this error before.

Modify body of Ninja Forms email.

$
0
0

I'm attempting to modify the email message body based on a users input to a form. I'm using the code shown here as a starting point: https://stackoverflow.com/questions/40345116/manipulate-ninja-forms-mail-body?answertab=votes#tab-top Unfortunately even the most rudimentary change to the message body does not seem to work, and I'm unable to find any additional documentation on the ninja_forms_action_email_message filter. Has anyone attempted to modify the email message body upon submission?

 

Here's what I'd like to achieve. If the user submits "Yes" to a question, then I would add a list item to the body of the email I send them. If they answer "No", then no list item would be added.

 

Thanks so much!

~Sarah

Counting files in a directory

Having trouble with opendir

$
0
0

Hi

I am have trouble with making this bit of code work

if(!isset($_GET['m'])) {
  die();
 }
$model = ($_GET['m']);

$images = "thumbs/$model/";
$big    = "gallery/$model/";

if($handle=opendir($images)) {
	while(false!==($file=readdir($handle))) {
	  if($file !=="."&&$file !=".."&&$file !=rtrim($big,"/")) {
	    $files[]=$file;
       }
    }
  closedir($handle);
 }

When I run this code nothing happens. I get this error message

PHP Warning:  opendir(thumbs/Honda/): failed to open dir: Permission denied in /var/www/html/Cars/index.php on line 56, referer: http://localhost/Cars

After some playing around I found that the line

$images = "thumbs/$model/";

is the problem. If I change it to

$images = "thumbs";

Then it works, my test was done using  "print_r($file);" This shows the array in the browser.

I have changed all the permissions in the thumbs directory and its sub-directories to 776.

This is also the case when using scandir()

 

Any help would be appreciated

Thank you

REST api using php - how to parse url resource id for POST

$
0
0
Hi

Looking to create an API using php and I have a question around POST:

I want to use a url of: http://localhost/customers as the end point for the api with the methods below:

GET /customers - to return all customers in json format
GET /customers/1 - to get customer with id of 1
POST /customers - to create a customer
PUT /customers/1 - to update customer with id of 1
DELETE /customers/1 - to delete customer with id of 1

And to create an address for customer 1:

POST /customers/1/address


Now how do I parse the the customer id from the URL for the POST request?

I can think of two ways to achieve this but not sure which is the correct way (if any)?

1. Use apache to rewrite the url from POST /customers/1/address to address.php?customerid=1 and then use $_GET[‘customerid’] and use that in combination with the POST data to then created the address?

2. Use apache to rewrite the url from POST /customers/1/address to address.php and then use the $_SERVER[‘REQUEST_URI’] to explode on forward slash and then use the value from the exploded array to use with the POST data to then creates the address for customer with id of 1.


Which way is best or is there a better way?

PHP Guzzle Graze Auth issue

$
0
0

hello,

im making request to a remote http server with Guzzle Graze (json rpc)

i make it this way:

    function __construct($hostname = 'http://127.0.0.1', $port = 9999, $user, $password)
    {
        $url = $hostname.':'.$port .'/json_rpc';
        $this->client = Client::factory(
            $url,
            [
                'defaults' => [
                    'auth' => [$user, $password]
                ]
            ]
        );

        $this->user = $user;
        $this->password = $password;
    }

but it not recognize the user and the password as a part of this request. how should i send the Password and username instead?
any solution please??

thanks

 


Returning files via an API

$
0
0

I am building an API which typically accepts and returns JSON.  I am also building the webserver which consumes the API json.  Both the webserver and api are using Slim.  The browser does not have the API's password, and authenticates with the webserver, and the webserver needs to relay the password to the API.  All works as expected.

Browser -----> WebServer   ----cURL---> API Server gets results and returns to WebServer which returns to browser.

I now have a need for the browser to be able to download a non-text file.

 

The browser http request to the webserver is trivial.

 

I haven't totally vetted how the API will respond to the request, but expect it will be pretty close to the following.  It doesn't look 100% the "Slim" way by overwriting the response, but hopefully it is good enought.

//Will not be accessed unless header authentication key as verified.

$app->get('/downloads/{id}', function(Request $request, Response $response, $args) {
    $file = $this->get('FileManager')->getFileName($args['id']);
    $response = $request->withHeader('Content-Description', 'File Transfer')
    ->withHeader('Content-Type', 'application/octet-stream')
    ->withHeader('Content-Disposition', 'attachment;filename="'.basename($file).'"')
    ->withHeader('Expires', '0')
    ->withHeader('Cache-Control', 'must-revalidate')
    ->withHeader('Pragma', 'public')
    ->withHeader('Content-Length', filesize($file));
    readfile($file);
    return $response;
});

The part that has got me stumped is how the webserver will need to forward the request to the api and then return the results to the browser client.

 

What is the best option to forward the request?  cURL (I am leaning against this one), file_get_content using stream context so I can send the security token header, exec() with wget, etc?. This part actually seems pretty straight forward.

 

After getting the response, I will somehow need to return the actual content plus the headers to the browser.  How do you see this looking?

 

If I want to keep it Slim looking on the webserver, I am thinking something like the following, but it doesn't necessary have to be.

$app->get(_VER_.'/guids/{guid}/logs/{type}/{name}', function (Request $request, Response $response) {
    $rsp=someHowGetContentWithHeaders();
    $headers = $response->getHeaders();
    foreach ($headers as $name => $values) {
        echo $name . ": " . implode(", ", $values);
    }
    return $response->withHeaders($rsp); //Unfortunately, I don't think such a "withHeaders" method exists :(
});
 

Thank you

 

 

 

Problem creating a table

$
0
0

Hello,

 

DataBase exists, but when I run the code there is no table in the DB yet I get the message :

Table users created successfully

 

when I run thr sql code in MtSql I get a message saying that there is an error in the 1st line

 

Here is the code: <?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "DB2018";
 
try{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "root" , "");
 
if (!$conn){
echo "Not connected to database ".$dbname;
}
   }
catch(PDOException $e){
echo $e->getMessage();
}
$sql = "CREATE TABLE IF NOT EXISTS Users (
  id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(25) NOT NULL,
  password VARCHAR(60) NOT NULL,
  reg_date TIMESTAMP,
  UNIQUE KEY 'username' ('username')
  )";
 
$conn->exec($sql);
 
if ($conn){
echo "Table users created successfully";
}else {
echo "Error creating table";
}
 
?>
 
 
What did I do wrong?

PHP Mapping

$
0
0

Hi all, I have a MySQL database of latitude and longitude coordinates that have an associated value. In this case it is temperature. There is a value for each 1.25km or so (effectively a grid). I was wondering if anyone knows of an efficient method to plot these points on a map to create a contour or smoothed temperature map? Are there any useful PHP libraries that would be effective in completing this? The data is simple with just a pair of coordinates and a value. 

 

Any info would be awesome. 

 

Thanks

Help with a script

$
0
0

Hi All,

 

Looking for some help if anyone can provide it.

 

I run this Twitter Bot.  https://twitter.com/OntarioRoads   A friend made this script years ago but he has passed and I've been able to keep it running just by sheer luck but I am trying to improve it since Twitter can do 280 char now.

 

How it works is the below script looks on this website for anything new  http://www.mto.gov.on.ca/english/traveller/trip/road_closures.shtml  and then makes it into a format like this and emails it out.

 

Subject: *-NEW-* HWY 401 Westbound Collector(s) [ McCOWAN ROAD -  ] - Disabled Vehicle  ...21:23:09

Body:

*-NEW-*
HWY 401 Westbound Collector(s) [ McCOWAN ROAD - ] - Disabled Vehicle
Highway: HWY 401
Direction: Westbound
From/At: McCOWAN ROAD
Lanes Affected: right lane and right shoulder blocked
Reason Disabled Vehicle
Last Change: Entered 2018-01-01 21:13

Event Start: January 01, 2018 21:13
====END====

 

To which then I grab the subject line and feed it into a basic command line windows app I have and tweet it out.

 

What I am looking to do is increase the info in the tweets now that I can.  I think if I can just add more info to the subject line and then tweet that out it would work but I am up for any ideas you may all have to make it better.  I don't make any money off this twitter bot you will see there are no ads etc..  

 

I've included a screenshot of a piece of the DB so you can see what all gets populated.  

 

DB.jpg

<?php
// Declare variables //
$debug = false;
//$url = "http://www.mto.gov.on.ca/english/traveller/conditions/rdclosure.htm";
$url = "http://www.mto.gov.on.ca/english/traveller/trip/road_closures.shtml";
//$url = "./road_closures.html";

$email_recip = "REMOVED";
#$email_recip = "REMOVEDt";
$email_from = "REMOVED";
$email_from_addr = "REMOVED";
$message_header = "";
$message_footer = "";
$arfield1 = array("summary","highway","direction","fromat","to","lanesaffected","trafficimpact","reason","others","eventstart","eventend");
$cntarfield1 = count($arfield1);
$timenow = date("Y-m-d H:i:s");
// Connect to database
$dbname = "mevents";
$dbuser = "REMOVED";
$dbpass = "REMOVED";
$datestamp = date("  ...G:i:s");

$link = mysql_connect('localhost',$dbuser,$dbpass);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname);


// DON'T EDIT PAST HERE UNLESS YOU KNOW WHAT YOU'RE DOING //
// MAIN PROGRAM ///
$webpage = read_web($url);
$content = find_data($webpage, "<!-- MIDDLE COLUMN", "</html>");
$content = find_data($content, "</div><a ", "</html>");
$curr_events = read_html_table($content,true);       // Parse the events HTML table

if ($curr_events["totalevents"]>0)
{
  $sql = "update mEvents set eventid = 'xRoadInfo' where eventid like 'RoadInfo%'";
  $result = mysql_query($sql);
}

for ($curr_event_num = 1; $curr_event_num <= $curr_events["totalevents"]; $curr_event_num++) {
  $send_email = false;     // Flag used to see if an email should be sent for new closure events
  $event_message = $message_header;
  $curr_event_found = false;

  if ($curr_events[$curr_event_num]["unscheduledevents"]==0)
  {
  	$sql = "select * from mEvents where eventid = '".($curr_events[$curr_event_num]["eventid"])."' limit 1";
  }
  else
  {
  	$unscd = explode("\n",$curr_events[$curr_event_num]["others"]["data"]);
  	$sql = "select * from mEvents where eventid='xRoadInfo' and highway='".$curr_events[$curr_event_num]["highway"]["data"]."' and direction='".$curr_events[$curr_event_num]["direction"]["data"]."' and fromat='".$curr_events[$curr_event_num]["fromat"]["data"]."'";
  	if ($unscd[0]!="") $sql .= " and others like '".$unscd[0]."%'";
  }
  $result = mysql_query($sql);
  if (mysql_num_rows($result)>0) $curr_event_found = true;

  if (!$curr_event_found) {    // Add the not found current event to the message
	$send_email = true;

	if ($curr_events[$curr_event_num]["eventend"]["data"]=="")
    {
        $event_message .= "*-NEW-*\n";
    }
	else
	{
		$event_message .= "-CLEARED-\n";
	}
	if ($debug) $event_message .= $curr_events[$curr_event_num]["eventid"];
	$sqlquery = "insert into mEvents (eventid,date_insert";
	$sqlval = "('".$curr_events[$curr_event_num]["eventid"]."','".$timenow."'";
	for ($a=0;$a<$cntarfield1;$a++)
	{
	   $sqlquery .= ",`".$arfield1[$a]."`";

	   $sqlval .= ",'".addslashes($curr_events[$curr_event_num][$arfield1[$a]]["data"])."'";
	   if ($curr_events[$curr_event_num][$arfield1[$a]]["data"]!="")
	   {
	     $event_message .= $curr_events[$curr_event_num][$arfield1[$a]]["field"]."".$curr_events[$curr_event_num][$arfield1[$a]]["data"]."\n";
	   }
	   if ($debug) $event_message .= "<br/>";
	}
	$sqlquery .= ") values".$sqlval.")";
	mysql_query($sqlquery);
	$event_message .= "====END====\n";
	$email_subject = "*-NEW-* ";
	$email_subject .= $curr_events[$curr_event_num]["summary"]["data"];
	$email_subject .= $datestamp;
	//$email_subject .= " #BellLetsTalk";

  } else {
	$row = mysql_fetch_array($result);
	if ($row["eventend"]=="")
	{
		if ($curr_events[$curr_event_num]["unscheduledevents"]==0)
		{
		if ($curr_events[$curr_event_num]["eventend"]["data"]!="")
		{
			$send_email = true;
			$event_message .= "-CLEARED-\n";
			if ($debug) $event_message .= $curr_events[$curr_event_num]["eventid"];
			$sqlquery = "update mEvents set date_update='$timenow'";
			for ($a=0;$a<$cntarfield1;$a++)
			{
			   $sqlquery .= ",`".$arfield1[$a]."`='".addslashes($curr_events[$curr_event_num][$arfield1[$a]]["data"])."'";
			   if ($curr_events[$curr_event_num][$arfield1[$a]]["data"]!="")
	   		   {
			     $event_message .= $curr_events[$curr_event_num][$arfield1[$a]]["field"]."".$curr_events[$curr_event_num][$arfield1[$a]]["data"]."\n";
			   }
			   if ($debug) $event_message .= "<br/>";
			}
			$sqlquery .= " where eventid='".$curr_events[$curr_event_num]["eventid"]."'";
			mysql_query($sqlquery);
			$event_message .= "====END====\n";
			$email_subject = "*-CLR-* ";
			$email_subject .= $curr_events[$curr_event_num]["summary"]["data"];
			$email_subject .= $datestamp;
			//$email_subject .= " #BellLetsTalk";

		}
		}
		else
		{
			$sqlquery = "update mEvents set eventid='".$curr_events[$curr_event_num]["eventid"]."' where id=".$row["id"];
			mysql_query($sqlquery);
		}
	}
 }
 $event_message .= $message_footer;

 //Send an email if there is a new/resolved event
 if ($send_email) {
	if ($debug) print ("Sending the message below to " . $email_recip . ", from \"" . $email_from . "\" <" .$email_from_addr . ">.\n" . $event_message . "\n");
	else mail ($email_recip, $email_subject, $event_message, "From: \"" . $email_from . "\" <" .$email_from_addr . ">");
 }

}
// FOUR LINES BELOW COMMENTED OUT  TO STOP REPEATING MESSAGE
//if ($curr_events["totalevents"]>0)
//{
 // $sql = "delete from mEvents where eventid = 'xRoadInfo'";
  //$result = mysql_query($sql);
//}

mysql_close();

// Functions //
//read_web - Read the web page
//           $strURL ==> URL of the webpage
function read_web($strURL)
{
  global $debug;
  $buffer = "";
  if($debug){ print("Reading \"$strURL\".\n"); }
  $fh = fopen($strURL, "rb");
  if ($fh === false) {
    return "";
  }
  while (!feof($fh)) {
    $buffer .= fread($fh, 1024);
  }
  fclose($fh);
  return $buffer;
} // end function read_web

// find)data - Gets a substring of the webpage by scraping the data
//             $strFile ==> text of the webpage
//             $strStart_Pattern ==> start of the substring
//             $strEnd_Pattern ==> end of the substring
function find_data($strFile,$strStart_Pattern,$strEnd_Pattern, $intStart_Position = 0)
{
  global $debug;
  if($debug){ print("Searching for \"$strStart_Pattern\"...\"$strEnd_Pattern\".\n<!-- //-->"); }
  $first_match = strpos($strFile,$strStart_Pattern, $intStart_Position);
  if ($first_match) {
    # find the begining of the tag
    for ($i = $first_match; $i>0;$i--) {
      $char = $strFile[$i];
      if ($char == "<" ) {
        $first_match = $i; //record the location of the tag
        break;
      }
    }
    $partialbuffer = substr($strFile,$first_match,strlen($strFile) - $first_match);
    # find the end of the sub string
    $second_match = strpos($partialbuffer,$strEnd_Pattern);
    return substr($partialbuffer,0,$second_match + strlen($strEnd_Pattern));
  } else {
    return(false);
  }
} //end function find_data

// read_html_table - Read the contents of an HTML table and return the array(s)
//                   strHTMLTable ==> HTML table text
//                   boolSkipFirstRow ==> Skip the first row if it contains column titles (true/false)
function read_html_table($strHTMLTable, $boolSkipFirstRow)
{
  global $debug,$arfield1,$cntarfield1;
  $arrevents = array();

  preg_match_all('/<a id="Event.+<\/table>/Us',$strHTMLTable,$dataevents);
  $dataevents = $dataevents[0];

  $countdataevents = count($dataevents);

  $j = 0;
  for($i=0; $i<$countdataevents; $i++)
  {
	preg_match('/<a id="Event([0-9]{4,8})">/', $dataevents[$i], $matches);
	$eventid = $matches[1];

	//if ($eventid>0)
	{
		$j++;
		$arrevents[$j]["eventid"] = $eventid;
		preg_match('/<th colspan="2">(.*)<\/th>/', $dataevents[$i], $matches);
		$arrevents[$j]["summary"]["field"] = "";
		$arrevents[$j]["summary"]["data"] = $matches[1];

		preg_match_all('/<tr>.+<\/tr>/Us',$dataevents[$i],$tr);
		$tr = $tr[0];
		$counttr = count($tr);

		for ($k=1;$k<$cntarfield1;$k++)
		{
			$arrevents[$j][$arfield1[$k]]["field"] = "";
			$arrevents[$j][$arfield1[$k]]["data"] = "";

		}
		if ($eventid>0) $arrevents[$j]["unscheduledevents"] = 0;
		else $arrevents[$j]["unscheduledevents"] = 1;

		for ($k=1;$k<$counttr;$k++)
		{
			preg_match_all('/<td.+<\/td>/Us',$tr[$k],$td);
			$td = $td[0];
			$td1 = cleandatafield(cleandata($td[0]));

			if (checkdatafield($td1)==1)
			{
				$arrevents[$j][$td1]["field"] = cleandata($td[0])." ";
				$arrevents[$j][$td1]["data"] = cleandata($td[1]);
			}
			else
			{
				if (cleandata($td[1])!="")
				{
					$arrevents[$j]["others"]["field"] = "";
					$arrevents[$j]["others"]["data"] .= cleandata($td[0])." ".cleandata($td[1])."\n";
				}
			}
		}
	}
  }
  echo "<br/>\ntotal ".$j;
  $arrevents["totalevents"] = $j;
  return $arrevents;
} //end function readhtmltable

function cleandata($x)
{
  $y = $x;
  $y = preg_replace('/<td.+>/U',"",$y);
  $y = str_replace("</td>","",$y);
  $y = str_replace("<strong>","",$y);
  $y = str_replace("</strong>","",$y);
  $y = str_replace("/r/n","",$y);
  $y = trim($y);

  return $y;
}
function cleandatafield($x)
{
  $y = $x;
  $y = str_replace("/","",$y);
  $y = str_replace(":","",$y);
  $y = str_replace(" ","",$y);
  $y = strtolower($y);
  return $y;
}
function checkdatafield($x)
{
  global $debug,$arfield1,$cntarfield1;
  $found = 0;
  for ($i=0;$i<$cntarfield1;$i++)
  {
	if ($x==$arfield1[$i]) $found = 1;
  }
  return $found;
}

print ("ClosedRoadScript");
print date("     G:i:s");
?>

Avoiding duplicate rows, using multiple columns, when Inserting via query...

$
0
0

My table primarily stores rows (basketball players) of First Name, Last Name, Grade and School.  Obviously, with over 1,000 there are many players with similar last names and similar first names, even a couple of instances over the years of players with same first and last name.  

 

I've done some searches here and elsewhere and found "on duplicate key" or "insert ignore into", and they don't seem to apply or I'm not able to get it to work.  My intention is to check first name, last name and grade before inserting a row from a form submission.

 

Do I need to SELECT the information I want to check concat(nameFirst, nameLast, grade) then compare it to the data I'm looking to insert?

"INSERT INTO a_players (school, grade, nameFirst, nameLast)
	VALUES ('".$data['school']."', '".$data['grade']. "', '" .$data['nameFirst']. "', '" .$data['nameLast']."')";

Viewing all 13200 articles
Browse latest View live