0

I am trying to fetch the data from database for a an input field product code and i need to use its value to update the rest of the column values in the database but instead it is creating a different record and in the value field of the input box 'named' code, it shows and undefined variable error, please help.

HTML code:
<div class="small-8 columns">
          <input type="text" id="right-label" placeholder="Product_code" 
 value="<?php echo "$pcode"?>" name="code">
        </div>
PHP Script:
 <?php
  $servername="localhost";
  $username="root";
  $password="";
  $dbname="bolt";
  try{
  $conn = new 
 PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


 if(isset($_POST["submit"])){
 $pcode = ($_POST["code"]);
 $pname = ($_POST["Pname"]);
 $pdesc = ($_POST["desc"]);
 $pimg = $_FILES["Img_name"]["temp_name"];
 $imgExt = strtolower(pathinfo($pimg,PATHINFO_EXTENSION));
 $valid_extensions = array('jpeg','jpg','png','gif','pdf');     
 $pqty = ($_POST["Pqty"]);
 $pprice = ($_POST["Pprice"]);
 $sql="UPDATE  products SET product_name=$pname,product_desc=$pdesc,
  product_img_name=$pimg,qty=$pqty,price 
  =$pprice) WHERE product_code=$pcode";
  $stmt = $conn->exec($sql);
 $stmt->execute();
  echo $stmt->rowCount() . "new records added succesfully";    
  }
  }
 catch(PDOException $e){

echo $sql . "<br>" . $e->getMessage(); 

}
$conn = null;      


?>
Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
nilesh
  • 1
  • 3
  • 5
    Please paste that error here which you are facing? –  Mar 27 '19 at 06:14
  • 1
    And a general remark: your code is _wide open_ to sql injection attacks. Please read and learn about the benefits of using the combination of "prepared statements" and "parameter binding". – arkascha Mar 27 '19 at 06:21
  • And the way you create the sql statement will most likely result in an invalid statement since you have not quote characters around operands of type string. – arkascha Mar 27 '19 at 06:22
  • I suspect that the undefined variable is `pcode` since I got this `Notice: Undefined variable: pcode`. If you put the PHP script before the HTML with its embedded PHP, that notice should not appear again. – slevy1 Mar 27 '19 at 06:41
  • @slevy1 i have placed the php script before the html code but still i am getting the error. – nilesh Mar 27 '19 at 07:23
  • @nilesh What variable does the error message say is undefined? – slevy1 Mar 28 '19 at 18:36

1 Answers1

0

$sql is declared within the if condition, if if(isset($_POST["submit"])){ is false, you will get this error because $sql is not within the scope. Declare it on above condition and initialize it.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78