Home > database >  SQL Statement does not insert the required value to table column
SQL Statement does not insert the required value to table column

Time:02-02

I'm inserting some values to a table using a sql statement. All the values get inserted, except the 'qty' column. When I do an echo for sql statement, it shows the value has been assigned to the sql statement. Table column data type is INT. Can anyone help me to spot the problem?

$it_code = $_POST['id']; 

//Prompt user to enter required qty
echo '<script>'; 
echo 'var qty = prompt("Enter Qty", "");';
echo '</script>';

//Get the item details from item table
$sqlString = "Select * from items where it_code='".$it_code."'";
$objItem = new Allfunctions;
$result = $objItem->retriveData($sqlString);

//Get the selected qty from java script to php variable
$qty = "<script>document.writeln(qty);</script>";
$user_id =$_SESSION['user_id'];  

//Insert to orders table
$sqlStringInsert = "INSERT INTO orders(user_id,it_code,qty,status,tr_timestamp) VALUES ('$user_id','$it_code','$qty','PENDING',CURRENT_TIMESTAMP())";
echo $sqlStringInsert;
$objItem->addToTable($sqlStringInsert,'Succsessfully added.','Error adding'); // This is a custom built method to insert data in to a table by taking the sql statement as the parameter

Following is the sql statement generated, enter image description here

Following is the table data. Qty is always 0 eventhood the sql statement had a value at qty column.

enter image description here

enter image description here

enter image description here

CodePudding user response:

Obligatory warning

The code as you have shown it should not be used in production as it is vulnerable to SQL-injection attacks. Preventing this is well covered on this site in other answers.

Answer

The issue is that the value of $qty you are injecting into your SQL is the string "<script>document.writeln(qty);</script>". You just can't see it because you are likely echoing it out to the browser to test it.

Wrap your echoing of the SQL statement in a call to htmlentities() (docs) to see what's actually happening.

Depending on the version and settings, MySQL is very forgiving of bad data being injected to a column. In this case, it sees a string of text being inserted to a numeric column, and just truncates it to 0. See this in action here:

CREATE TABLE Foo (
  Id INT,
  Qty INT
 );
 
INSERT INTO Foo(Id, Qty) VALUES (1, 'a string of text');

SELECT * FROM Foo; -- returns a row (1, 0)

https://www.db-fiddle.com/f/dEoaYGEyXEjs6ocVBwyyyr/1

  • Related