SketchyTurtle
SketchyTurtle

Reputation: 425

How to insert post data into mysql db with php?

I have been troubleshooting this for multiple hours and am not sure why this is not working. I am trying to send a http post with a Qt app and using this as my php script:

<?php
$con=mysqli_connect("*.mysql.eu2.*.com:3306","*****","****","****");

if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$price = filter_input(INPUT_POST, 'price', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$type = filter_input(INPUT_POST, 'type', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
$stock= filter_input(INPUT_POST, 'stock', FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);

  $currentid = mysqli_insert_id();

  if (trim($id) == '') {
    exit('id cannot be empty!');
  }
  if (trim($price) == '') {
    exit('price cannot be empty!');
  }
  if (trim($type) == '') {
    exit('type cannot be empty!');
  }
  if (trim($stock ) == '') {
    exit('stock cannot be empty!');
  }

  $result = "insert into ammo (ammoType,storeId,ammoStock,ammoPrice) VALUES ('".$type."','".$id."','".$stock."','".$price."');";

   mysqli_query($result) or die("Could not insert data");



mysqli_close($con);
?>

I have been at a point before where I was getting success but then the values were not actually showing up in my db. Thanks, -David

Upvotes: 5

Views: 323

Answers (1)

Funk Forty Niner
Funk Forty Niner

Reputation: 74217

Firstly, you're not connecting to your query.

mysqli_query($result)

That function requires 2 parameters, and the DB connection first.

mysqli_query($con,$result)

Read the manual: http://php.net/manual/en/mysqli.query.php

and you need to check for errors. We don't know what's inside your HTML form and whether you are using a POST method and if your elements bear the right name attributes.

If you get undefined index notices, you'll know what to go for.

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.

This doesn't help you

or die("Could not insert data");

this does

or die(mysqli_error($con));

You should also be using a prepared statement.

N.B.:

Should MySQL complain about data going in as Jack's Bar & Grill, then you will need to escape your data.

  • Any which way, you should.

Upvotes: 5

Related Questions