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.
Bubbles
3,8051 gold badge26 silver badges25 bronze badges
-
date('m/d/Y h:i:s a'); is short for date('m/d/Y h:i:s a', time());jtheman– jtheman2012年11月04日 23:09:40 +00:00Commented 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.Chris Henry– Chris Henry2012年11月04日 23:39:51 +00:00Commented Nov 4, 2012 at 23:39
1 Answer 1
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!
answered Nov 4, 2012 at 23:08
Green Black
5,0571 gold badge19 silver badges29 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
nickhar
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.Marc B
$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.
default