I have problem about putting mysql into a function showMsg(). The mysql is working fine if it is not wrapped by function showMsg(), but when I wrap it with function showMsg(), it gives error message "Warning: mysql_query(): supplied argument is not a valid". How to put mysql inside a php function? Below is my codes :
<?php
function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
<div>
<?php showMsg(); ?>
</div>
?>
Never use global.
Pass $connection into your function as an argument.
Logic and representation should be separated.
Read about MVC: here or here.
Global variables are evil, never use it. If someone suggests it - ignore all their answers.
You probably need:
global $connection;
(Inside the function, that is.)
See Variable Scope
As everyone mentioned, the issue has to do with variable scoping. Instead of add global $connection; you could consider a more OOP approach and consider:
A: passing the $connection variable into the function.
B: placing related functions in a class and pass the DB connection into the Class constructor.
for example:
class YourClass {
private $connection;
public function __construct($connection) {
$this->connection = $connection;
}
public function showMsg(){
$query2 = "SELECT id, message, username, datetime FROM messageslive ORDER BY id DESC LIMIT 20";
$result2 = mysql_query($query2,$this->connection) or die (mysql_error());
confirm_query($result2);
$num = mysql_num_rows($result2);
while($msginfo = mysql_fetch_array($result2)){
echo $msginfo['message'];
echo $msginfo['username'];
}
}
}
I don't have enough rep to comment. But I also like OZ_'s answer :)
$connection variable has no value assigned. The following code should solve your problem (add it at the beginning of the function):
global $connection;
But you should be aware of the fact, that using globals is not a good idea and you may want to:
(preferably) pass $connection variable within the parameter of the function, or
move $connection declaration from outside the function just into the function (if it does not cause additional problems), or
redeclare $connection variable within the function (again: if it will not cause additional problems),
Because variables are local to functions. You need to add this inside your function:
global $connection;
Simply put, functions ignore outside variables due to variable scope. You must let the declare the variable as being from the outside by using global or you can send $connection through a parameter.
Related
In a file, I connect to the database (using PDO) and the resulting connection is called $db, so that queries I run would be something like
$db->query("SELECT money FROM bank_accounts");
However, if I put that line in a function, $db isn't defined so it doesn't work.
Obviously reconnecting to the database in each function isn't the best way to accomplish db calls in a function so how would I accomplish something like
function stealMoney($acctID) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
You need to use $db in a function.
And its not defined in the function, so definitely, $db is inaccessible/undefined to the function body.
There are two ways to deal it:
1) Pass $db as an argument to the function.
So, the function body becomes:
function stealMoney($acctID, $db = NULL) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
And the function call:
stealMoney($acctID, $db);
2) Use global:
In this case, you can use $db as a global.
So, the function body becomes:
function stealMoney($acctID) {
global $db;
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
So that, your function will read this variable from outside and can access it.
I have a simple core class that is being used for core functions to a small web app. I have defined some constants in the class - which has mostly static functions - and I am wanting to set / edit these constants outside of the class, example:
class core{
const connection = '';
public static function someSqlScript(){
$sql = "SELECT * FROM sometable WHERE someconditions";
$exec = mysqli_query(self::connection, $sql);
}
}
Now, I want to be able to set the connection constant so that it references a mysql connection object, which (by means of another script), has already been assigned to the variable $con, so essentially I am after something like this:
core::connection = $con; //send connection for use in class
core::someSqlScript(); //should not perform the MySQL query using conneciton $con as above
Any help is greatly appreciated, I am used to using non static functions and variables within classes, but the static functions with constants has got me.
Thanks to all.
The meaning of constant is, that you can't change it. You want a static variable:
class core{
public static $connection = '';
public static function someSqlScript(){
$sql = "SELECT * FROM sometable WHERE someconditions";
$exec = mysqli_query(self::$connection, $sql);
}
}
core::$connection = $con;
core::someSqlScript();
Note the public static $connection instead of const connection and self::$connection instead of self::connection (also core::$connection instead of core::connection).
The idea of constants is, that they cannot be changed after their definition.
$EODQuery = "SELECT * FROM EOD WHERE Symbol LIKE '$start' LIMIT 1 OFFSET $limit";
$EODRes = $mysqli->query($EODQuery);
I get an error, but not when i directly query the database.
<?php $i = 0; while($i <= 4) { $EODRow = getEOD("A%",$i); $i++; echo $EODRow; } ?>
Your error message has nothing to do with the query itself. What's happening is this: You're calling a method query() on the $mysqli object - however, PHP thinks that it's not actually an object.
The reason for this can be:
You forgot to create this object (See http://www.php.net/manual/en/mysqli.connect.php). Here's an example:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
You mistyped the variable name, so your mysqli object is actually called something else.
The code you show is within a function or a method, but your $mysqli object is in the global scope. In this case, you should "load" it into the function scope, like this:
function doStuff() {
global $mysqli;
$mysqli->query(...);
}
For more information regarding variable scope, see this link: http://php.net/manual/en/language.variables.scope.php
On the first look it seems like you have forgotten to instantiate $mysqli, that leads to $mysqli not being an object, so you cant execute the query() method.
I am trying to make a function to pull a page's content from a MySQL table using a PDO Prepare statement. My code works just fine outside of the function I defined, but no matter what I do it will not work within the function - I receive the following error:
Fatal error: Call to a member function prepare() on a non-object in /home/tappess1/public_html/pages/stations.php on line 6
Here is my PHP:
function getPageContent($page) {
$st = $db->prepare("SELECT * FROM content WHERE title LIKE ?");
$st->execute(array($page));
$pageContent = $st->fetch();
$text = wordwrap($pageContent['content'], 100, "\n");
$tabs = 4;
$text = str_repeat(chr(9), $tabs) . str_replace(chr(10), chr(10) . str_repeat(chr(9), $tabs), $text);
echo $text;
}
and then
<?php getPageContent(Main);?>
I have even tried using a query instead of prepare statement, simply calling getPageContent() and I receive the same error.
Thanks!
You are trying to access the variable $db which is outside your function's scope.
Either re-initialize your database within the function $db = new PDO...., or - probably better and easier in your case - import the global variable:
function getPageContent($page) {
global $db;
Where and how to best store the global database object is subject of a lot of discussion. If you want to get into it, here is one place to start (there are many others on SO, too). But if you're just getting into PHP, I'd say using the global variable is fine.
The variable $db is not known within your function.
I have this function:
function query_dp($sql) {
$link = mysql_connect('localhost', $bd_id, $bd_pass);
mysql_select_db("$bd");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
return mysql_query($sql) or die(mysql_error());
mysql_close($link);
}
In the main program, when I try to do:
echo mysql_num_rows(query_db($sql));
I get as return
1
When I do not encapsulate that code in a function and use it directly to the main program, I get the number of rows fetched.
The function is not returning a Resource but an... integer? WTF?
Any help would be greatly appreciated!
Your variables $bd_id, $bd_pass and $bd are not visible inside the function since they are probably declared in the global scope and not the local scope of that function.
You would either make the global variables accessible by using the global keyword, by using the $GLOBALS variable, or by passing them to the function.
your call to mysql_close means that you no longer have a link to the mysql resource that you need in mysql_num_rows
The problem is in "or" operator. Your function returns result of "mysql_query($sql) or die(mysql_error())" expression, which is 1 or 0. I suggest you to use something like this:
$query_result = mysql_query($sql);
if (!$query_result) {
die(mysql_error());
}
return $query_result;
Also last line of this function "mysql_close($link)" is never called.
This doesn't directly answer your question, but you shouldn't use the original mysql interface. it is clunky and procedural. Take a look at the mysqli interface. Don't try to wrap the old functions if you have a language supported standard that already does this :D
You above code just becomes
$m = new MysqlI(...);
$rc = $m->query(...);
echo $rc->num_rows();