1

I have an array as follows:

 Array ( [item-name] => SM58 
         [make] => Shure 
         [model] => SM58 
         [qty] => 5 
         [status] => Available 
       )

And I want to change it into a database query such as:

INSERT INTO `Inventory`(`item-name`, `make`, `model`, `qty`, `status`) VALUES ('SM58','Shure','SM58','5',[Available])

I just can't quite work out how I achieve it.

2
  • To make it easier, you can also do INSERT INTO `Inventory` SET `item-name`='SM58', .... Commented Jan 17, 2014 at 19:48
  • you listed 7 fields and 5 value !!! Commented Jan 17, 2014 at 19:50

2 Answers 2

3

You can use PDO:

$stmt = $PDOinstance->prepare("
  INSERT INTO `Inventory` (`item-name`, `make`, `model`, `qty`, `status`) 
  VALUES (:item-name, :make, :model, :qty, :status)
");
$stmt->execute($yourArray);
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain the parts of this to me so I can understand it for the future? PDO means...? ->execute sends it to the database?
@user3207974, PDO stands for PHP Data Objects. Basically, this is a safe and pretty easy way to access your database. Please see the documentation for more info: php.net/manual/en/class.pdo.php
-1

Try this

   foreach($array as $index => $value){
    $fields .= "`".$index."`".",";
    $values .= "'".mysql_real_escape_string($value)."'".","; //This escapes for mysql
    }
    $fields = rtrim($fields,",");
    $values = rtrim($values,',');
    $sql = "INSERT INTO `Inventory`($fields) VALUES ($values)";

However as the mysql_* function is depreciated you would be better using the above post with PDO and prepared statements or you could use the mysqli_* function along with prepared Statements. Below are the links to the two resources.

PDO: http://www.php.net/manual/en/book.pdo.php MySQLI: https://www.php.net/mysqli

4 Comments

Please, do not post answers without SQL escaping. This creates enormous liabilities in any applications that use this code.
@tadman the answer wasn't asking about escaping they was asking about a solution. This is entirely there choice to escape the string before they create an array. Also I am unable to specify an escape unless we know whether they are using PDO, MySQL or mysqli functions which they do not specify
The solution always involves escaping. When in doubt, give an example in PDO if you're trying to promote the use of that. Look at t1gor's example here which does it correctly. Yours, unfortunately, perpetuates the worst habits of PHP developers.
@tadman i have noted how to escape for mysql_* function but as it is depreciated i have noted that PDO with prepared statements would be better to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.