0

I am very very new to MySQL, I have two arrays, whose output looks like this:

Array
(
    [0] => Product/service
    [1] => Product/service
    [2] => Non-profit organization
    [3] => Community
    [4] => Company
    [5] => Non-profit organization
    [6] => Website
    [7] => Book
    [8] => Arts/humanities website
    [9] => Public figure
)

I have a table (with a variable name) and two column names, the above array is called "category" and I would like to have a table where there would be a column named "category" which would just list these elements. I have tried the code below but it does nothing:

mysql_connect('127.0.0.1','root','') or die(mysql_error());;
mysql_select_db("DBName") or die(mysql_error());;
mysql_query("CREATE TABLE `".$tablename."` ( category VARCHAR(30), name VARCHAR(30))");

foreach($category as $k=>$v)
{
    mysql_query("INSERT INTO".$tablename. "(category) VALUES".$v); 

} 
4
  • I do not see where $tablename is being set Commented Dec 21, 2012 at 2:45
  • You should avoid using mysql_* functions. As of PHP 5.5.0 they are deprecated. Use something like PDO or MySQLi Commented Dec 21, 2012 at 2:45
  • Look at the INSERT syntax. INSERT INTO (category) VALUES ('value') You're missing (). Commented Dec 21, 2012 at 2:46
  • You need some error checking. if (!mysql_query(...)) echo mysql_error() and you'll see it's complaining about syntax errors in the query. Commented Dec 21, 2012 at 2:47

2 Answers 2

2

I understand that you're new so let me see if I can help you. Some people like being creating with their php, as opposed to me where I like it clear and concise as to what is happening.

So here try this:

foreach($categories as $key=>$val){

      $sql_I = "INSERT INTO categories SET category = '{$val}'";
      $res_I = mysql_query($sql_I) or die(mysql_error());
}
Sign up to request clarification or add additional context in comments.

Comments

1

You just need some more white space and some extra punctuation:

mysql_query('INSERT INTO '.$tablename. ' (category) VALUES ('.$v.')'); 

Comments

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.