Can not find record in databaseHow does database indexing work?How can I prevent SQL injection in PHP?Can I concatenate multiple MySQL rows into one field?How do I connect to a MySQL Database in Python?Find duplicate records in MySQLRetrieving the last record in each group - MySQLFinding duplicate values in a SQL tableWhat are the options for storing hierarchical data in a relational database?Serializing / Unserializing a PHP Array'Invalid parameter number' error using bindParam to create an mySQL query

Why didn't Boeing produce its own regional jet?

Why was the shrinking from 8″ made only to 5.25″ and not smaller (4″ or less)?

Arrow those variables!

Short story with a alien planet, government officials must wear exploding medallions

How to tell a function to use the default argument values?

Can my sorcerer use a spellbook only to collect spells and scribe scrolls, not cast?

Size of subfigure fitting its content (tikzpicture)

Reverse dictionary where values are lists

Determining Impedance With An Antenna Analyzer

Solving a recurrence relation (poker chips)

Im going to France and my passport expires June 19th

Can we compute the area of a quadrilateral with one right angle when we only know the lengths of any three sides?

What do you call someone who asks many questions?

Little known, relatively unlikely, but scientifically plausible, apocalyptic (or near apocalyptic) events

What mechanic is there to disable a threat instead of killing it?

Is it acceptable for a professor to tell male students to not think that they are smarter than female students?

What is the most common color to indicate the input-field is disabled?

Is it possible to create a QR code using text?

What about the virus in 12 Monkeys?

Personal Teleportation: From Rags to Riches

What does the expression "A Mann!" means

Assassin's bullet with mercury

How much of data wrangling is a data scientist's job?

Is there a hemisphere-neutral way of specifying a season?



Can not find record in database


How does database indexing work?How can I prevent SQL injection in PHP?Can I concatenate multiple MySQL rows into one field?How do I connect to a MySQL Database in Python?Find duplicate records in MySQLRetrieving the last record in each group - MySQLFinding duplicate values in a SQL tableWhat are the options for storing hierarchical data in a relational database?Serializing / Unserializing a PHP Array'Invalid parameter number' error using bindParam to create an mySQL query













1















I have the following problem: I am receiving a GET variable in a url. If the variable GET arrives, I send the contents of the variable to my controller.



My controller first brings the whole "sales" table, then I look for the record that has the same content of the GET variable in a column. Finally, I update the status of that record I found.



But nothing happens, and I do not know what I'm doing wrong.



I leave the code:



PHP file where the variable GET is received:



if(isset( $_GET['number']))

$number = $_GET['number'];

$response = CartController::ctrShowSales($number);

echo $response;




PHP Controller:



static public function ctrShowSales($number)

$table = "sales";

$respuesta = CartModel::mdlShowSales($table);

$find = 0;

foreach ($response as $key => $value)

if ($value["number"] == $number)

$find = 1;
$id = $value["id"];

break;





if ($find == 1)

$response2 = CartModel ::mdlUpdateRecord($table, $id);
return $response2;

else return "Did not find";




PHP Model:



static public function mdlShowSales($table)

$stmt = Conection::conect()->prepare("SELECT * FROM $table");

$stmt -> execute();

return $stmt -> fetch();

$stmt -> close();

$tmt =null;



static public function mdlUpdateRecord($table, $id)

$stmt = Conection::conect()->prepare("UPDATE $table SET status = :status WHERE $id = :$id");

$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->bindParam(":status", "Verified", PDO::PARAM_STR);

if($stmt -> execute())

return "ok";

else

return "error";



$stmt -> close();

$stmt = null;











share|improve this question
























  • 📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

    – tadman
    Mar 8 at 22:37











  • Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

    – Bryan
    Mar 8 at 22:37












  • You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

    – tadman
    Mar 8 at 22:37






  • 1





    @Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

    – spencer7593
    Mar 8 at 22:48







  • 1





    WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

    – ArtisticPhoenix
    Mar 8 at 22:52
















1















I have the following problem: I am receiving a GET variable in a url. If the variable GET arrives, I send the contents of the variable to my controller.



My controller first brings the whole "sales" table, then I look for the record that has the same content of the GET variable in a column. Finally, I update the status of that record I found.



But nothing happens, and I do not know what I'm doing wrong.



I leave the code:



PHP file where the variable GET is received:



if(isset( $_GET['number']))

$number = $_GET['number'];

$response = CartController::ctrShowSales($number);

echo $response;




PHP Controller:



static public function ctrShowSales($number)

$table = "sales";

$respuesta = CartModel::mdlShowSales($table);

$find = 0;

foreach ($response as $key => $value)

if ($value["number"] == $number)

$find = 1;
$id = $value["id"];

break;





if ($find == 1)

$response2 = CartModel ::mdlUpdateRecord($table, $id);
return $response2;

else return "Did not find";




PHP Model:



static public function mdlShowSales($table)

$stmt = Conection::conect()->prepare("SELECT * FROM $table");

$stmt -> execute();

return $stmt -> fetch();

$stmt -> close();

$tmt =null;



static public function mdlUpdateRecord($table, $id)

$stmt = Conection::conect()->prepare("UPDATE $table SET status = :status WHERE $id = :$id");

$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->bindParam(":status", "Verified", PDO::PARAM_STR);

if($stmt -> execute())

return "ok";

else

return "error";



$stmt -> close();

$stmt = null;











share|improve this question
























  • 📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

    – tadman
    Mar 8 at 22:37











  • Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

    – Bryan
    Mar 8 at 22:37












  • You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

    – tadman
    Mar 8 at 22:37






  • 1





    @Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

    – spencer7593
    Mar 8 at 22:48







  • 1





    WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

    – ArtisticPhoenix
    Mar 8 at 22:52














1












1








1








I have the following problem: I am receiving a GET variable in a url. If the variable GET arrives, I send the contents of the variable to my controller.



My controller first brings the whole "sales" table, then I look for the record that has the same content of the GET variable in a column. Finally, I update the status of that record I found.



But nothing happens, and I do not know what I'm doing wrong.



I leave the code:



PHP file where the variable GET is received:



if(isset( $_GET['number']))

$number = $_GET['number'];

$response = CartController::ctrShowSales($number);

echo $response;




PHP Controller:



static public function ctrShowSales($number)

$table = "sales";

$respuesta = CartModel::mdlShowSales($table);

$find = 0;

foreach ($response as $key => $value)

if ($value["number"] == $number)

$find = 1;
$id = $value["id"];

break;





if ($find == 1)

$response2 = CartModel ::mdlUpdateRecord($table, $id);
return $response2;

else return "Did not find";




PHP Model:



static public function mdlShowSales($table)

$stmt = Conection::conect()->prepare("SELECT * FROM $table");

$stmt -> execute();

return $stmt -> fetch();

$stmt -> close();

$tmt =null;



static public function mdlUpdateRecord($table, $id)

$stmt = Conection::conect()->prepare("UPDATE $table SET status = :status WHERE $id = :$id");

$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->bindParam(":status", "Verified", PDO::PARAM_STR);

if($stmt -> execute())

return "ok";

else

return "error";



$stmt -> close();

$stmt = null;











share|improve this question
















I have the following problem: I am receiving a GET variable in a url. If the variable GET arrives, I send the contents of the variable to my controller.



My controller first brings the whole "sales" table, then I look for the record that has the same content of the GET variable in a column. Finally, I update the status of that record I found.



But nothing happens, and I do not know what I'm doing wrong.



I leave the code:



PHP file where the variable GET is received:



if(isset( $_GET['number']))

$number = $_GET['number'];

$response = CartController::ctrShowSales($number);

echo $response;




PHP Controller:



static public function ctrShowSales($number)

$table = "sales";

$respuesta = CartModel::mdlShowSales($table);

$find = 0;

foreach ($response as $key => $value)

if ($value["number"] == $number)

$find = 1;
$id = $value["id"];

break;





if ($find == 1)

$response2 = CartModel ::mdlUpdateRecord($table, $id);
return $response2;

else return "Did not find";




PHP Model:



static public function mdlShowSales($table)

$stmt = Conection::conect()->prepare("SELECT * FROM $table");

$stmt -> execute();

return $stmt -> fetch();

$stmt -> close();

$tmt =null;



static public function mdlUpdateRecord($table, $id)

$stmt = Conection::conect()->prepare("UPDATE $table SET status = :status WHERE $id = :$id");

$stmt->bindParam(":id", $id, PDO::PARAM_INT);
$stmt->bindParam(":status", "Verified", PDO::PARAM_STR);

if($stmt -> execute())

return "ok";

else

return "error";



$stmt -> close();

$stmt = null;








php mysql sql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 23:15







John J.

















asked Mar 8 at 22:33









John J.John J.

828




828












  • 📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

    – tadman
    Mar 8 at 22:37











  • Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

    – Bryan
    Mar 8 at 22:37












  • You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

    – tadman
    Mar 8 at 22:37






  • 1





    @Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

    – spencer7593
    Mar 8 at 22:48







  • 1





    WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

    – ArtisticPhoenix
    Mar 8 at 22:52


















  • 📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

    – tadman
    Mar 8 at 22:37











  • Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

    – Bryan
    Mar 8 at 22:37












  • You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

    – tadman
    Mar 8 at 22:37






  • 1





    @Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

    – spencer7593
    Mar 8 at 22:48







  • 1





    WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

    – ArtisticPhoenix
    Mar 8 at 22:52

















📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

– tadman
Mar 8 at 22:37





📎: "It looks like you're writing your own ORM. Have you considered using one that's already written, tested, and widely supported like RedBeanPHP, Doctrine, Propel or Eloquent?"

– tadman
Mar 8 at 22:37













Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

– Bryan
Mar 8 at 22:37






Use the database to find the record. Not php. Also, this issue is probably that the function mdlShowSales doesn't return all record. Try fetchAll.

– Bryan
Mar 8 at 22:37














You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

– tadman
Mar 8 at 22:37





You're loading the entire table into memory to find a single record. This could bring down your server if you have a large number of records. Instead do a focused query WHERE id=:id LIMIT 1 and get the specific row you need.

– tadman
Mar 8 at 22:37




1




1





@Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

– spencer7593
Mar 8 at 22:48






@Chipster: I think $id is the value in the column, not the column name. We see it referenced in the bindParam. I think the SQL was meant to id = :id ... but that's just a guess.

– spencer7593
Mar 8 at 22:48





1




1





WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

– ArtisticPhoenix
Mar 8 at 22:52






WHERE $id = :$id - is a syntax error 100%, consider $id=1 WHERE 1 = :1 In fact without that : they would have a big issue.... UPDATE ... WHERE 1=1 in other words your one colon away from wrecking your table, because $id is always equal to $id which would basically update every row in your DB!

– ArtisticPhoenix
Mar 8 at 22:52













2 Answers
2






active

oldest

votes


















2














In addition to the other answers I would add this simple method to your models,



protected static $tables = ['sales'];

final static public function ckTable($table)
if(false !== ($index = array_search($table, static::$tables, true)))
return $tables[$index]; //return your table value

throw new Exception('Unknown Table');


static public function mdlShowSales($table)
//here you can clearly see the table is being handled
$safeTable = self::ckTable($table); //use a different var here


$stmt = Conection::conect()->prepare("SELECT * FROM $safeTable");
....

//or $stmt = Conection::conect()->prepare("SELECT * FROM ".self::ckTable($table));



Right now you have only the fact that you hard coded this, in your controller:



$table = "sales";


All it would take is to one day make this mistake in a controller



//here you cannot tell if this is safe to do or not as you cannot see how the query is done.
static public function somepage($table)
$respuesta = CartModel::mdlShowSales($table);



And you would be open to SQL Injection even if you prepare the query.



Right now it's just Improbable that, that will happen, we should make this impossible.



Also, this is basically what you are doing:



//everything under PHP Controller can be done with this sql:
SELECT id FROM sales WHERE number = :number LIMIT 1
/*
SELECT * FROM sales
foreach ($response as $key => $value)
if ($value["number"] == $number) //-- WHERE number = :number
$find = 1;
$id = $value["id"]; //-- SELECT id
break; //-- LIMIT 1


*/

//mdlUpdateRecord
UPDATE sales SET status = :status WHERE id = :id


So why not just do this



UPDATE sales SET status = :status WHERE number = :number LIMIT 1


Basically I am just rewording your code into just SQL, you can do it however you want. I think maybe ordering will be an issue here with Limit 1 if your order is different and you have multiple number rows for the same value. But I don't know what your DB looks like to say for sure, this is true with your original code as well.






share|improve this answer
































    1














    change in your model to fetch results associative:



    static public function mdlShowSales($table)

    $stmt = Conection::conect()->prepare("SELECT * FROM $table");

    $stmt -> execute();

    return $stmt -> fetch(PDO::FETCH_ASSOC);

    $stmt -> close();

    $tmt =null;




    and then your controller:



    static public function ctrShowSales($number)

    $table = "sales";

    $respuesta = CartModel::mdlShowSales($table);



    foreach ($response as $value)

    if ($value["number"] == $number)

    $response2 = CartModel ::mdlUpdateRecord($tabla, $id);
    return $respuesta2;





    return "Did not find";







    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071934%2fcan-not-find-record-in-database%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      In addition to the other answers I would add this simple method to your models,



      protected static $tables = ['sales'];

      final static public function ckTable($table)
      if(false !== ($index = array_search($table, static::$tables, true)))
      return $tables[$index]; //return your table value

      throw new Exception('Unknown Table');


      static public function mdlShowSales($table)
      //here you can clearly see the table is being handled
      $safeTable = self::ckTable($table); //use a different var here


      $stmt = Conection::conect()->prepare("SELECT * FROM $safeTable");
      ....

      //or $stmt = Conection::conect()->prepare("SELECT * FROM ".self::ckTable($table));



      Right now you have only the fact that you hard coded this, in your controller:



      $table = "sales";


      All it would take is to one day make this mistake in a controller



      //here you cannot tell if this is safe to do or not as you cannot see how the query is done.
      static public function somepage($table)
      $respuesta = CartModel::mdlShowSales($table);



      And you would be open to SQL Injection even if you prepare the query.



      Right now it's just Improbable that, that will happen, we should make this impossible.



      Also, this is basically what you are doing:



      //everything under PHP Controller can be done with this sql:
      SELECT id FROM sales WHERE number = :number LIMIT 1
      /*
      SELECT * FROM sales
      foreach ($response as $key => $value)
      if ($value["number"] == $number) //-- WHERE number = :number
      $find = 1;
      $id = $value["id"]; //-- SELECT id
      break; //-- LIMIT 1


      */

      //mdlUpdateRecord
      UPDATE sales SET status = :status WHERE id = :id


      So why not just do this



      UPDATE sales SET status = :status WHERE number = :number LIMIT 1


      Basically I am just rewording your code into just SQL, you can do it however you want. I think maybe ordering will be an issue here with Limit 1 if your order is different and you have multiple number rows for the same value. But I don't know what your DB looks like to say for sure, this is true with your original code as well.






      share|improve this answer





























        2














        In addition to the other answers I would add this simple method to your models,



        protected static $tables = ['sales'];

        final static public function ckTable($table)
        if(false !== ($index = array_search($table, static::$tables, true)))
        return $tables[$index]; //return your table value

        throw new Exception('Unknown Table');


        static public function mdlShowSales($table)
        //here you can clearly see the table is being handled
        $safeTable = self::ckTable($table); //use a different var here


        $stmt = Conection::conect()->prepare("SELECT * FROM $safeTable");
        ....

        //or $stmt = Conection::conect()->prepare("SELECT * FROM ".self::ckTable($table));



        Right now you have only the fact that you hard coded this, in your controller:



        $table = "sales";


        All it would take is to one day make this mistake in a controller



        //here you cannot tell if this is safe to do or not as you cannot see how the query is done.
        static public function somepage($table)
        $respuesta = CartModel::mdlShowSales($table);



        And you would be open to SQL Injection even if you prepare the query.



        Right now it's just Improbable that, that will happen, we should make this impossible.



        Also, this is basically what you are doing:



        //everything under PHP Controller can be done with this sql:
        SELECT id FROM sales WHERE number = :number LIMIT 1
        /*
        SELECT * FROM sales
        foreach ($response as $key => $value)
        if ($value["number"] == $number) //-- WHERE number = :number
        $find = 1;
        $id = $value["id"]; //-- SELECT id
        break; //-- LIMIT 1


        */

        //mdlUpdateRecord
        UPDATE sales SET status = :status WHERE id = :id


        So why not just do this



        UPDATE sales SET status = :status WHERE number = :number LIMIT 1


        Basically I am just rewording your code into just SQL, you can do it however you want. I think maybe ordering will be an issue here with Limit 1 if your order is different and you have multiple number rows for the same value. But I don't know what your DB looks like to say for sure, this is true with your original code as well.






        share|improve this answer



























          2












          2








          2







          In addition to the other answers I would add this simple method to your models,



          protected static $tables = ['sales'];

          final static public function ckTable($table)
          if(false !== ($index = array_search($table, static::$tables, true)))
          return $tables[$index]; //return your table value

          throw new Exception('Unknown Table');


          static public function mdlShowSales($table)
          //here you can clearly see the table is being handled
          $safeTable = self::ckTable($table); //use a different var here


          $stmt = Conection::conect()->prepare("SELECT * FROM $safeTable");
          ....

          //or $stmt = Conection::conect()->prepare("SELECT * FROM ".self::ckTable($table));



          Right now you have only the fact that you hard coded this, in your controller:



          $table = "sales";


          All it would take is to one day make this mistake in a controller



          //here you cannot tell if this is safe to do or not as you cannot see how the query is done.
          static public function somepage($table)
          $respuesta = CartModel::mdlShowSales($table);



          And you would be open to SQL Injection even if you prepare the query.



          Right now it's just Improbable that, that will happen, we should make this impossible.



          Also, this is basically what you are doing:



          //everything under PHP Controller can be done with this sql:
          SELECT id FROM sales WHERE number = :number LIMIT 1
          /*
          SELECT * FROM sales
          foreach ($response as $key => $value)
          if ($value["number"] == $number) //-- WHERE number = :number
          $find = 1;
          $id = $value["id"]; //-- SELECT id
          break; //-- LIMIT 1


          */

          //mdlUpdateRecord
          UPDATE sales SET status = :status WHERE id = :id


          So why not just do this



          UPDATE sales SET status = :status WHERE number = :number LIMIT 1


          Basically I am just rewording your code into just SQL, you can do it however you want. I think maybe ordering will be an issue here with Limit 1 if your order is different and you have multiple number rows for the same value. But I don't know what your DB looks like to say for sure, this is true with your original code as well.






          share|improve this answer















          In addition to the other answers I would add this simple method to your models,



          protected static $tables = ['sales'];

          final static public function ckTable($table)
          if(false !== ($index = array_search($table, static::$tables, true)))
          return $tables[$index]; //return your table value

          throw new Exception('Unknown Table');


          static public function mdlShowSales($table)
          //here you can clearly see the table is being handled
          $safeTable = self::ckTable($table); //use a different var here


          $stmt = Conection::conect()->prepare("SELECT * FROM $safeTable");
          ....

          //or $stmt = Conection::conect()->prepare("SELECT * FROM ".self::ckTable($table));



          Right now you have only the fact that you hard coded this, in your controller:



          $table = "sales";


          All it would take is to one day make this mistake in a controller



          //here you cannot tell if this is safe to do or not as you cannot see how the query is done.
          static public function somepage($table)
          $respuesta = CartModel::mdlShowSales($table);



          And you would be open to SQL Injection even if you prepare the query.



          Right now it's just Improbable that, that will happen, we should make this impossible.



          Also, this is basically what you are doing:



          //everything under PHP Controller can be done with this sql:
          SELECT id FROM sales WHERE number = :number LIMIT 1
          /*
          SELECT * FROM sales
          foreach ($response as $key => $value)
          if ($value["number"] == $number) //-- WHERE number = :number
          $find = 1;
          $id = $value["id"]; //-- SELECT id
          break; //-- LIMIT 1


          */

          //mdlUpdateRecord
          UPDATE sales SET status = :status WHERE id = :id


          So why not just do this



          UPDATE sales SET status = :status WHERE number = :number LIMIT 1


          Basically I am just rewording your code into just SQL, you can do it however you want. I think maybe ordering will be an issue here with Limit 1 if your order is different and you have multiple number rows for the same value. But I don't know what your DB looks like to say for sure, this is true with your original code as well.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 23:48

























          answered Mar 8 at 23:30









          ArtisticPhoenixArtisticPhoenix

          18.3k11226




          18.3k11226























              1














              change in your model to fetch results associative:



              static public function mdlShowSales($table)

              $stmt = Conection::conect()->prepare("SELECT * FROM $table");

              $stmt -> execute();

              return $stmt -> fetch(PDO::FETCH_ASSOC);

              $stmt -> close();

              $tmt =null;




              and then your controller:



              static public function ctrShowSales($number)

              $table = "sales";

              $respuesta = CartModel::mdlShowSales($table);



              foreach ($response as $value)

              if ($value["number"] == $number)

              $response2 = CartModel ::mdlUpdateRecord($tabla, $id);
              return $respuesta2;





              return "Did not find";







              share|improve this answer



























                1














                change in your model to fetch results associative:



                static public function mdlShowSales($table)

                $stmt = Conection::conect()->prepare("SELECT * FROM $table");

                $stmt -> execute();

                return $stmt -> fetch(PDO::FETCH_ASSOC);

                $stmt -> close();

                $tmt =null;




                and then your controller:



                static public function ctrShowSales($number)

                $table = "sales";

                $respuesta = CartModel::mdlShowSales($table);



                foreach ($response as $value)

                if ($value["number"] == $number)

                $response2 = CartModel ::mdlUpdateRecord($tabla, $id);
                return $respuesta2;





                return "Did not find";







                share|improve this answer

























                  1












                  1








                  1







                  change in your model to fetch results associative:



                  static public function mdlShowSales($table)

                  $stmt = Conection::conect()->prepare("SELECT * FROM $table");

                  $stmt -> execute();

                  return $stmt -> fetch(PDO::FETCH_ASSOC);

                  $stmt -> close();

                  $tmt =null;




                  and then your controller:



                  static public function ctrShowSales($number)

                  $table = "sales";

                  $respuesta = CartModel::mdlShowSales($table);



                  foreach ($response as $value)

                  if ($value["number"] == $number)

                  $response2 = CartModel ::mdlUpdateRecord($tabla, $id);
                  return $respuesta2;





                  return "Did not find";







                  share|improve this answer













                  change in your model to fetch results associative:



                  static public function mdlShowSales($table)

                  $stmt = Conection::conect()->prepare("SELECT * FROM $table");

                  $stmt -> execute();

                  return $stmt -> fetch(PDO::FETCH_ASSOC);

                  $stmt -> close();

                  $tmt =null;




                  and then your controller:



                  static public function ctrShowSales($number)

                  $table = "sales";

                  $respuesta = CartModel::mdlShowSales($table);



                  foreach ($response as $value)

                  if ($value["number"] == $number)

                  $response2 = CartModel ::mdlUpdateRecord($tabla, $id);
                  return $respuesta2;





                  return "Did not find";








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 23:10









                  godotgodot

                  1,38121329




                  1,38121329



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55071934%2fcan-not-find-record-in-database%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme