开发者

Php database models

<?php
 class ann {

      public function __construct($context, $orgs_id, $created_at) {
         $this->context = $context;
         $this->orgs_id = $orgs_id;
         $this->created_at = $created_at;
     }

     function create(){
         $createann = mysql_query("INSERT INTO anns(context,
 orgs_id, created_at)
 VALUES('$this->context',
 $this->orgs_id, '$this->created_at'");
         if($createann) echo "Duyuru Başarıyla Eklendi"; else echo "Duyuru
 Eklenemedi";
     }
     function read($id){
         $readann = mysql_query("SELECT * FROM anns WHERE id = $id");
         $context = mysql_result($readann,0, "context");
         $orgs_id = mysql_result($readann,0, "orgs_id");
         $created_at = mysql_result($readann,0,
 "created_at");

         $ann = new ann($context, $orgs_id, $created_at);

         return $ann;
     }
     function update($id, $context){
         $updateann = mysql_query("UPDATE anns SET context =
 '$context' WHERE id = $id");
         if($updateann) echo "Update success"; else echo
 "Update failed";
     }
     function delete($id){
         $deleteann = mysql_query("DELETE FROM anns WHERE id
 = $id");
         if($deleteann) echo "Delete success"; else echo "Delete not success";
     }
     //crud fonksiyonlari burda bitiyor 
}

?>

There is something wrong with our logic here but we are very new to php. We tried to create rails like models, but it think something w开发者_JS百科ith our class-object notation is wrong. So the code did not work. We cannot even create any object with it. Thank you guys


context, orgs_id and created_at must be should be first declared either as public, private or protected before you use them.

In your create method, you don't filter user input. This may cause to your application SQL injection, you have to you always filter user input. Use either mysql_real_escape_string or prepared statment by PDO.

You may check this tutorial.


two things (which maybe only apply to your codesample here):

  1. In your sample, you dont close your Class, because the last "}" is commented out.
  2. You never opened a connection to your database, so the query would fail.


a few observations:

declaring the attributes in the constructor is possible, but it's not elegant. I'd rather do:

class ann {
  private $context;
  private $orgs_id;

the "->" operator won't work inside a string. You'll need to concatenate the query:

"INSERT INTO anns(context,orgs_id, created_at) VALUES('".$this->context."',".$this->orgs_id".", '".$this->created_at."'"

but be careful on sql injection

The rest should be fine! Good Luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜