2

I'm having trouble getting a mysql query to work within a function. I don't understand why this works:

    $datetime = date('m/d/Y h:i:s a', time());

    $query = "INSERT INTO 1_posts (title_post, time_post, key_words_post, content_post) VALUES ('$title2', '$datetime', '$keywords2', '$text2')";

    mysql_query($query, $con);

but this does not:

function insert_post($title2, $keywords2, $text2)
{

    $datetime = date('m/d/Y h:i:s a', time());

    $query = "INSERT INTO 1_posts (title_post, time_post, key_words_post, content_post) VALUES ('$title2', '$datetime', '$keywords2', '$text2')";

    mysql_query($query, $con);

}

Of course, I have a connection to the db, and I am calling the function. I tried to debug with some echos and I found out that the function stops ant mysql_query, but I have no idea why.

2
  • date('m/d/Y h:i:s a'); is short for date('m/d/Y h:i:s a', time()); Commented Nov 4, 2012 at 23:09
  • The mysql* functions are deprecated in php. You you should be using mysqli* functions or PDO. Additionally, you may want to implement some sort of error handling. Commented Nov 4, 2012 at 23:39

1 Answer 1

8
function insert_post($title2, $keywords2, $text2)
{
 global $con;
    $datetime = date('m/d/Y h:i:s a', time());

    $query = "INSERT INTO 1_posts (title_post, time_post, key_words_post, content_post) VALUES ('$title2', '$datetime', '$keywords2', '$text2')";

    mysql_query($query, $con);

}

is a dirty way to get it working ($con is not set in your function). But please please take a look at PDO!

Sign up to request clarification or add additional context in comments.

4 Comments

Please point out how this is different from and/or fixes the issues.
How about: Declaring $con as a global var enables access to it within the function. I'm more inclined to go with PDO though too.
$con is not necessary in mysql calls. it'll default to using the last opened connection if one isn't explicitly specified. you only need the $con parameter if you've got multiple connections open and have to choose between them.
In the code given in the question, $con is being passed to mysql_query, but is not declared as a global.

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.