2016-06-06 37 views
0

所以我有一個PHP腳本,集成了api從json結果中廢棄信息。該工具會執行搜索查詢,查找位於特定狀態的所有配置文件,然後保存所有返回的鏈接並開始循環並逐個執行它們以查看其中的數據並檢索所需的數據。在這個過程結束時,我試圖讓結果寫入我的數據庫。假設我收集$ firstname和$ lastname,當工具運行時,我發現它永遠不會錯過任何信息,但它往往會在數據庫中寫入重複信息,可能只是$ firstname而不是$ lastname。當它這樣做時,它將會寫入該條目兩次,一次寫入所有信息,另一次只寫入部分信息。考慮到它總是不管收集什麼我需要我試圖找出一個if或else語句或其他類型的觸發器,所以在它寫入我的表之前,PHP腳本將檢查以確保所有可用字段已填充與信息。如果他們寫了,如果不是,它什麼都不做。PHP來執行SQL空白數據庫條目

這裏是我迄今爲止..

 if($firstname = ""){ 
     echo ""; } 
     else { 
     $sql_S = "INSERT INTO records (firstname, lastname, email, phone, duns, cage, expirationdate, businessname, address, city, state, zip, naics) VALUES ('{$firstname}','{$lastname}','{$email}','{$phone}','{$duns}','{$cage}','{$expirationDate}','{$businessName}','{$samAddress}','{$samCity}','{$samState}','{$samZip}','{$naics_num}')"; 
     $res_CE = mysql_query($sql_S); 
         } 

它似乎並沒有工作,進一步我不能讓它檢查多個領域,如$名字,姓氏$。

任何輸入,非常感謝。

謝謝你的時間。

+1

[Little Bobby](http://bobby-tables.com/)說[你的腳本存在SQL注入攻擊風險。](http://stackoverflow.com/questions/60174/how-can-i - 防止-SQL注入功能於PHP)。即使[轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)是不安全的! –

+1

請[停止使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php)。 [這些擴展](http://php.net/manual/en/migration70.removed-exts-sapis.php)已在PHP 7中刪除。瞭解[編寫]​​(http://en.wikipedia.org/ wiki/Prepared_statement)語句[PDO](http://php.net/manual/en/pdo.prepared-statements.php)和[MySQLi](http://php.net/manual/en/mysqli.quickstart .prepared-statements.php)並考慮使用PDO,[這真的很簡單](http://jayblanchard.net/demystifying_php_pdo.html)。 –

+1

'if($ firstname ==「」){',double equal。 –

回答

0

這裏有一些解決方案。

很多,如果是

if($firstname == "" || $lastname == "") echo "error"; ... 

僞驗證:

foreach(['firstname', 'lastname'] as $var) { 
    if ($$var == "") echo "error"; ... 
} 

一類與規則:

$rules = ['firstname' => 'notEmpty', 'lastname' => 'notEmpty']; 
$validator = new Validator($rules); 

$myObj->firstname = $firstname; 
$myObj->lastname = $lastname; 
... 

try { 
    $validator->validate($myObj); 
} ... 

class Validator { 

    protected $rules; 
    protected $errors; 

    public function __construct($rules) { 
     $this->rules = $rules; 
    } 

    public function validate($obj) { 
     $this->errors = []; 
     $vars = get_object_vars($obj); 
     foreach($this->rules as $attr => $arrayOfRules) { 
      $rule = explode("|", $arrayOfRules); 
      foreach($rule as $r) { 
       switch($r) { 
        case "notEmpty": 
         if($this->ruleNotEmpty($vars[$attr])) { 
          $this->errors['notEmpty'][] = $attr; 
         } 
         break; 
        default: 
         break; 
       } 
      } 
     } 
     if(count($this->errors)) { 
      //@TODO return all errors with messages here 
      throw new Exception("Errors found"); 
     } 
     return true; 
    } 

    protected function ruleNotEmpty($data) { 
     return $data != ""; 
    } 
} 

這是某種方式來做到這一點。有很多框架和組件已經做了一些驗證,但這是一個方向。