This question already has answers here:
Executing mysqli_query inside a function
(2 answers)
Closed 7 years ago.
I'm having some problems performing a mysql query inside a php function. The error I am getting is
Notice: Undefined variable: link in C:\path\api\inc\restFunctions.php on line 16
There are several files calling each other so I will attempt to outline the necessary information.
URL Accessed:
localhost/serverList/api/rest.php?action=allServers
serverList/api/rest.php
<?php
include 'inc/restFunctions.php';
$possibleCalls = array('allServers','allEnvs','allTypes','false');
if(isset($_GET['action'])){
$action = $_GET['action'];
}
else{
$action = 'false';
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers();
break;
case 'allEnvs':
$return = allEnvs();
break;
case 'allTypes':
$return = allTypes();
break;
case 'false':
$return = falseReturn();
break;
}
}
serverList/api/inc/restFunctions.php
<?php
include ('inc/config.php');
function allServers(){
$serverInfoQuery = "SELECT * FROM servers"
$allServerResults = $link->query($serverInfoQuery);
$json = array();
while($row = $allServerResults->fetch_assoc()){
$json[]['serverID'] = $row['serverID'];
$json[]['environment'] = $row['environment'];
$json[]['type'] = $row['type'];
$json[]['serverIP'] = $row['serverIP'];
$json[]['serverDescription'] = $row['serverDescription'];
$json[]['serverCreatedBy'] = $row['serverCreatedBy'];
$json[]['serverCreatedDtTm'] = $row['serverCreatedDtTm'];
$json[]['serverUpdatedBy'] = $row['serverUpdatedBy'];
$json[]['serverUpdatedDtTm'] = $row['serverUpdatedDtTm'];
}
$jsonResults = json_encode($json);
return $jsonResults;
}
?>
serverList/api/inc/config.php
<?php
$host = 'localhost';
$user = 'userName';
$password = 'password';
$database = 'database';
$link = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
?>
I have verified that the query being called works. I also verified that the connection info (masked above) works by using a different page of this software that queries the db.
I'm assuming I must have missed a quote or paren somewhere, but I'm baffled as to where it might be.
The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:
global $link;
See more here:
http://php.net/manual/en/language.variables.scope.php
In my opinion using global variables is not a good solution. You might override $link ($link is rather usual name for a variable you may be using for another purposes) variable in some scope by accident, resulting in lot's of confusion and difficult debugging.
Just pass it as a function parameter - much cleaner and easier to read:
function AllServers($link) {
$serverInfoQuery = "SELECT * FROM servers";
$allServerResults = $link->query($serverInfoQuery);
//More PHP code
}
if(in_array($action,$possibleCalls)){
switch ($action){
case 'allServers':
$return = allServers($link);
break;
}
}
To be honest, even better solution would be using some generic classes/functions to establish your mysql connection like so:
class DB {
private static $link = null;
public static function getConnectionResource() {
//In that way we "cache" our $link variable so that creating new connection
//for each function call won't be necessary
if (self::$link === null) {
//Define your connection parameter here
self::$link = new mysqli($host, $user, $password, $database);
}
return self::$link;
}
}
function getAllServers() {
$link = DB::getConnectionResource();
//Preform your query and return results
}
Use global variable
function allServers(){
global $link
...
...
...
... your code follows
Related
This is my fonction.php :
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
?>
But it does not works with my code when I want to call this function :
<?php
include("fonctions.php");
?>
<html>
<form name="inscription" method="post" action="form.php">
xxx : <input type="text" name="xxx"/> <br/>
xxx: <input type="text" name="xxx"<br/>
<input type="submit" name="valider" value="OK"/>
</form>
<?php
if (isset ($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
connect();
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
}
?>
</body>
</html>
Before I was using mysql_connect and it was more simple, my fonction was like this :
<?php
function connect(){
$base = mysql_connect ('localhost', 'root', '');
mysql_select_db ('MaBase', $base) ;
}
?>
What is the best way to create a good include with my mysql params ? THanks all for any help.
Include obligatory statement about using PDO or mysqli and prepared statements when using variables in your SQL statements...
You aren't passing your function a SQL statement to use, or otherwise defining $sql in the function.
function connect($sql){
For defining it, and then to call it
$sql_statement="select foo from bar where bee=1";
$res=connect($sql_statement);
You'll also need your function to return some sort of value.
What I've done is create a generic function that takes a SQL statement and an array of positional parameters, the function then uses PDO and prepared statement to execute the query using the parameters, and then returns an array with appropriate data. $ret[0] is a bool to indicate success, if false then [2..N] contain(s) error message(s), if true then [2..N] contains returned record set for a select, number of rows affected for update, delete, and last_insert_id for an insert statement (detected by using regular expression on the query string)
This is written once, and require_once()'d all across 15 web apps for the college I work at.
To this you i suggest you to use OOP approach i am just suggesting this with my own way you can try it with different ways no problem in my answer i am using two class first class does all the database connection and mysqli real escape conversion and staff other class is query class it's handle all the querying staff
database.class.php
//databaseconnection
class DatabaseConnections{
function connect($databaseNaem){
try{
return $connection=mysqli_connect("localhost","user","password",'database');
}catch(Exception $e){
echo 'Message:'.$e->getMessage();
}
}
function CloseConnection($dataObject){
if(mysqli_close($dataObject)){
return 1;
}else{
echo "coudn't Close the Database Connection";
}
}
function convert($connection , $vari){
return mysqli_real_escape_string($connection,$vari);
}
}
//queryclass
class Query{
function queryNoresult($stmt){
if($stmt->execute()){
return 1;
}
}
function queryNumOfRows($stmt){
$stmt->execute();
$result = $stmt->get_result();
return mysqli_num_rows($result);
}
function QueryResult($stmt){
$stmt->execute();
$result = $stmt->get_result();
return $result;
}
function illcallothers($stmt,$callto){
if($callto == 1){
return $this->queryNoresult($stmt);
}if ($callto==2) {
return $this->queryNumOfRows($stmt);
}
if($callto == 3){
return $this->QueryResult($stmt);
}
}
}
as you can see at the end i have created a function call illcallothers and this function takes what you want do with your query it's takes only 2 parameters
Created statement
The function number
there 3 option in this
if you call $query->illcallothers($stmt,1) this call the function
only for execute best for delete and insert because it's return 1 if
it's success
if you call $query->illcallothers($stmt,2) this call the function that return number of rows that returned nothing else best for check it data is availbe before using while
if you call $query->illcallothers($stmt,3) this will return result set from your query
Now lets go to your problem execution
//first you have to require the database file
require_once('database.class.php');
//Then you have to create object from them
$mymainObj = new DatabaseConnections();//obj from database
$connetion = $mymainObj->connect('databasename');//this will return a connection Object
$stmt = $connection->stmt_init(); //then the statement you need the connection object to this
$query = new Query();//object from the query class
//i am not going to put form part in here it will get messy
$titre= $mymainObj->convert($connection,$_POST['xxx']);//calling mysqli realescape funciton in databaseconnection
$auteur=$mymainObj->convert($connection,$_POST['xxx']);
//now you have create the sql
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES(?,?)';//when using stmt this how we tell mysql that we have this much parameters and then we pass them after preparing
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$author);
if($query->illcallothers($stmt,1)){
echo "Query Success";
}
}
It should be,
<?php
function connect(){
$servername = "localhost";
$username = "xxx";
$password = "xxxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
return false;
}else{
return $conn;
}
}
?>
Your query should be,
<?php
if (isset($_POST['valider'])){
$titre=$_POST['xxx'];
$auteur=$_POST['xxx'];
$connection = connect();
if($connection != false){
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
$result=$connection->query($sql);
if($result){
echo "done";
}else{
echo "faild";
}
}
}
?>
You should take a tour/learn the basics of OOP
It seems like all the above answers missed that you have two variables with the same name:
$sql = 'INSERT INTO xxx (`xxx`, `xxx`) VALUES("'.$xxx.'","'.$xxx.'")';
Both are called $xxx
IF YOU thought that the names of your public variables shoulden't be shown publicly here, and changed them to 'xxx', then please edit your question and don't change them to the same name (e.g change to $name and $password for example)
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 4 years ago.
I want to show all the records from the DB on my website, it's a PDO built website. I want it to show all the records so you can see what's in the DB.
This is how my DB looks like
The connection is set up in a different document called config.php
<?php
date_default_timezone_set('Europe/Amsterdam');
error_reporting(E_ALL & ~ E_DEPRECATED);
ini_set('display_errors', 'ON');
$CONFIG = array();
$CONFIG['root'] = '/home/tom/public_html';
$CONFIG['rootwebsite'] = '/home/tom/public_html';
$CONFIG['website'] = 'https://###';
$CONFIG['dbhost'] = 'localhost';
$CONFIG['dbuser'] = '####';
$CONFIG['dbpass'] = '####';
$CONFIG['dbdatabase'] = 'tom';
?>
This is the code I have in a php document and tried using. The problem is it won't show anything on my website (this is a different file than the file my website is):
<?php
class Forum {
private $dbh; //dbh = database handler.
public function __construct($database) {
$this->dbh = $database;
}
public function getForum() {
$getTopic = $dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getUTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
}
}
You are not calling the right $connection variable. It should be $this->dbh
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
Also you are mixing the variables after execute(). You should use easy to remember variables.
public function getForum() {
try {
$getTopic = $this->dbh->prepare("SELECT * FROM topics ORDER BY id DESC");
$getTopic->execute();
$topics = $getTopic->fetchAll();
foreach ($topics as $topic) {
echo $topic['onderwerp'] . '<br />';
}
} catch (PDOException $pdoEx) {
echo $pdoEx->getMessage();
exit;
} catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
}
Also since you are not passing any variable to your query, there is no point of using prepare(). Just call query() instead.
For error reporting add,
error_reporting(E_ALL); #place at the top of the script
Also you should consider using a proper IDE like PHPstorm or Netbeans, as they would easily point out unsed variables
As suggested by #adpro, here is a link, to help with debugging
If I run this code , the value in the SQL base is added 5x.
Code:
function token($u) {
include('../config.php');
$token=md5(rand()+$u);
$date = date('Y-m-d H:i:s');
$tokenQuery = 'INSERT INTO '.$prefix.'tokens(`token`, `user`, `date`) VALUES ("'.$token.'","'.$u.'","'.$date.'")';
$mysqli->query($tokenQuery);
}
token ('filips');
See how it look my SQL base
My config is:
$host = 'my server';
$user = 'my username';
$pass = 'my password';
$data = 'pn_16734995_filipcms_demo';
$prefix = 'fc_';
$mysqli = new mysqli($host,$user,$pass, $data);
$mysqli->query("SET NAMES 'utf8'" );
if ($mysqli->connect_errno) {
echo "Server not working: (" . $mysqli->connect_errnor. ") " . $mysqli->connect_error;
}
Nothing in your code will make the INSERT statement happen 5 times. However, if you echo "function called"; inside of your function, you can see if the function is being called 5 times, then you can figure out where up the line your function is being called 5 times.
you don't need to include the whole file just pass $mysqli as a parameter or put it in a global scope;
function token($u,$mysqli) {
}
OR
function token($u) {
global $mysqli;
}
I have build a website and communicate with actionscript. in actionscript i'm build a function to call php function and post a variables for load data from mysql database.The problem is when i call actionscript function and post variables to php.The php side i call $_POST['action']; for receive a variables from actionscript side but when i want to see this Post $_POST['action']; it error like this
Notice: Undefined index: action in C:\wamp\www\MPA-EM\bin\model.php on line 3
and this is a action script function to call php:
public function SelectData(TBN:String,TYPE:String):void{
var myrequest:URLRequest = new URLRequest("http://localhost/MPA-EM/bin/model.php");
myrequest.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.tablename = TBN;
variables.action = TYPE;
myrequest.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, dataOnLoad);
loader.addEventListener(Event.CANCEL, dataError);
try{
loader.load(myrequest);
}catch(e:Error){
Alert.show(e.toString());
}
}
public function dataOnLoad(evt:Event):void
{
Alert.show(evt.target.data.Result);
if(evt.target.data.Result) {
DText.text = 'ok';
} else DText.text = "Error in select submitted data";
//status is a custom flag passed from back-end
}
public function dataError(e:Event) :void{
DText.text = e.target.errormsg;
}
and this is a php function side model.php:
<?php
//test for recive
$actionW = $_POST['action'];//error this line.
echo $actionW;
// end test
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
echo $action;
switch($action) {
case 'select' :
$tablename = clean($_POST['tablename']);
selectedData($tablename);
break;
case 'blah' : blah();break;
}
}
function selectedData($table){
// create connection
$connection = mysql_connect("localhost", "root", "") or die ("Couldn't connect to the server.");
// select database
$db = mysql_select_db("ideaddcom_maps", $connection) or die ("Couldn't select database.");
// create SQL
$sql = 'SELECT * FROM '.$table;
// execute SQL query and get result
echo $sql;
$sql_result = #mysql_query($sql, $connection) or die ("Couldn't execute query.".mysql_error());
$row = mysql_fetch_object($sql_result);
foreach($row as $cname => $cvalue){
echo "Result=$cvalue";
}
// free resources and close connection
mysql_free_result($sql_result);
mysql_close($connection);
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
?>
What wrong? Pls any idea for this and Thank.
I do not know if you've found a solution for your problem, but this may help someone else.
1 - Take a look here, It can help you : Submitting scores from AS3 to PHP/SQL - #Error 2101
2 - To avoid PHP Undefined index Notice, you should always verify if your var is set before use it, like what you've done at line 7.
3 - Avoid all outputs that are not used by your AS script in the PHP script because AS will just get the first output.
4 - If you use a for or foreach loop to get data in your PHP script, you should do like this because echo that will send data to AS should be executed once :
$result = '';
$sep = ',';
foreach($row as $cname => $cvalue){
$result .= $cvalue . $sep;
}
echo 'Result='.$result;
My script requires connections to several databases. Some parts only need to connect to one, which is all fine and dandy, however in some cases I need to perform queries on different database in a single script execution.
Currently I'm doing something like this:
function db_connect($which) {
if($which == "main") {
$maindb = mysqli_connect(HOSTNAME_1, USER, PASSWORD, MAIN_DB);
return $maindb;
} elseif($which == "stats") {
$statsdb = mysqli_connect(HOSTNAME_2, USER, PASSWORD, STATS_DB);
return $statsdb;
}
}
$maindb = db_connect("main");
$statsdb = db_connect("stats");
I maintain the actual hostname, username, password and db name in a config file full of constants.
I then use the respective links on different queries.
Is there a cleaner way to do this?
Quite good, although you shoul try not to duplicate your code :
function db_connect($which) {
if($which == "main") {
$host = HOSTNAME_1;
$db = MAIN_DB;
} elseif($which == "stats") {
$host = HOSTNAME_2;
$db = STATS_DB;
} else {
throw new Exception('unknown db');
}
return mysqli_connect($host, USER, PASSWORD, $db);
}
$maindb = db_connect("main");
$statsdb = db_connect("stats");
That seems to be ok. An alternative would be to use the class mysqli instead of the functions in order to manipulate objects instead of identifiers.
You could store your databaseconfigs in arrays and use that. That's how codeigniter does it.
function get_database_config(){
$config['main']['hostname'] = "host1";
$config['main']['user'] = "user1";
$config['main']['password'] = "pass1";
$config['main']['database'] = "database1";
$config['stats']['hostname'] = "host2";
$config['stats']['user'] = "user2";
$config['stats']['password'] = "pass2";
$config['stats']['database'] = "database2";
return $config;
}
function db_connect($db)
{
$config = get_database_config();
return mysqli_connect(
$config[$db]['hostname'],
$config[$db]['user'],
$config[$db]['password'],
$config[$db]['database']
);
}
If you don't want to work with an associative array and prefer to work with constants, you could name your constants as MAIN_HOSTNAME, STATS_HOSTNAME, ... and use constant($which . '_HOSTNAME') as input for mysqli_connect().