Why can't i write my MySQL database using a 'required' function? - php

I'm using a file called "lib.php" in which i have defined many functions.
One of these functions is the following :
function dbconn()
{
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
}
In all the .php pages of my website, i've been using this dbconn() function, and it seemed to work fine for reading information from the database. However, when trying to write information, it seems to pose a problem. Specifically, the following code did not function :
<?php
require ("lib.php");
set_time_limit(60);
session_start();
dbconn();
$sql="update `city` set end_dt=now() where city_id='$_POST[killcity]'";
$result=mysql_query($sql,$conn) or die(mysql_error());
header("Location: manipulate.php");
?>
It says that conn is an undefined variable, whereas it should be defined by dbconn() in lib.php.
So, i've found a way around this, by instead creating a new php file called dbconn.php, which contains the exact same thing as dbconn(), and by inserting require ("dbconn.php"); instead of dbconn();.
But i'm still wondering : why did the original way not work ?

You could add a return statement for the function, through you could use global variable in a function, that's not good practice. If you want to, see how global variable works.
function dbconn() {
$servername="127.0.0.1";
$username="root";
$conn=mysql_connect($servername,$username)or die(mysql_error());
mysql_select_db("profit",$conn) or die(mysql_error());
return $conn;
}
$conn = dbconn();

Related

Deleting data with php

I'm trying to use a delete function for my sql table, but the php backend code throws lots of errors. Ive tried it several ways and non seem to work.
session_start(); //starts the session
if($_SESSION['user']){ //checks if user is logged in
}
else
{
header("location:index.php"); // redirects if user is not logged in
}
if($_SERVER['REQUEST_METHOD'] == "GET")
{
mysql_connect("localhost", "root","") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$StaffID=$_GET['StaffID'];
$sql = "DELETE FROM volunteer WHERE StaffID = '$StaffID'" ;
if(mysql_query($sql))
{
echo"Record deleted successfully.";
}
else
{
echo "ERROR: Could not execute $sql.";
mysql_error ($link);
}
mysql_close();
}
This seemed to work, how would I then get this function to return me to the original table with the record deleted?
You should consider to recycle your PHP knowledge. There is a lot of things in it that are not used anymore, for example mysql library. Try to use PDO in the next projects.
There are a few problems with your code.
1- In mysql_query function you are passing a variable $link that apparently is not defined before. So, you should check it.
2 - The order of the variables in mysql_query function is not correct. See the link below:
http://php.net/manual/pt_BR/function.mysql-query.php
3 - You are using a constant or a string in your where clause. You should to use the variable defined one line before.
I saw theses problems. Fix them, try again and post the results,
Regards,

What would cause include_once to break my code in PHP with MySQL?

The code below was not working:
public function __construct($thread_id)
{
require_once('../private/mysqli_connect.php');
require_once('../php_classes/class_message.php');
$this->thread_id=$thread_id;
$q="SELECT *
FROM message_thread_name
WHERE thread_id=2";
if($r=#mysqli_query($dbc, $q))
{
while($row=mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$this->poster=$row['name'];
$this->subject=$row['thread_subject'];
}
}
$qm="SELECT message_id
FROM message
WHERE thread_id=$this->thread_id";
if($rm=#mysqli_query($dbc, $rm))
{
while($rowm=mysqli_fetch_array($rm, MYSQLI_ASSOC))
{
$message=new message($rowm['message_id']);
array_push($this->messages, $message);
}
}
}
I ran out of ideas for fixing it, so I changed require_once('../private/mysqli_connect.php'); to require('../private/mysqli_connect.php');, and much to my surprise, it worked. Any ideas as to why that may be?
Thanks.
When you use require_once PHP will check if the file has already been included, and if so, not include (require) it again. You can read it here.
So whats the problem here?
From your problem statement, I am assuming you have created another instance of this class before, or you have already included mysqli_connect.php somewhere else. And in your mysqli_connect.php you have created the connection link something like.
$dbc= mysqli_connect( ... );
So when you using require_once as the mysqli_connect.php is not loading again, your $dbc variable remain undefined. and your query does not work. But when you use require instead of require_once the file loaded again, and new connection created again, and your code works.
NB: Though changing to require, solved your problem, you should not use it like this. It will create new connection to your database, each time you create new instance of your class. For your thought: you can try creating something like this

"Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource"

I am getting this error:
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource
Here's my Connection.php :
$userDB_server = "";
$userDB_user = "";
$userDB_password = "";
$userDB_database = "";
$connection = mysql_connect("$userDB_server","$userDB_user","$userDB_password") or die ("Unable to establish a DB connection");
$userDB = mysql_select_db("$userDB_database", $connection) or die ("Unable to establish a DB connection");
$gameDB_server = "";
$gameDB_user = "";
$gameDB_password = "";
$gameDB_database = "";
$gameDB_connection = mysql_connect("$gameDB_server","$gameDB_user","$gameDB_password", true) or die ("Unable to establish a DB connection");
$gameDB = mysql_select_db("$gameDB_database", $gameDB_connection) or die ("Unable to establish a DB connection");
Here's my function :
require_once('Connection.php');
$findQuery = sprintf("SELECT * FROM `Keys` WHERE `ID` = '$gID'");
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
The error is on "$findResult = mysql_query($findQuery, $connection) or die(mysql_error());"
But I don't see a problem anywhere.
What I've tried :
I've tried with and without the "true" on the second connection,
didn't seem to make a difference anywhere.
Echoing the $connection and $gameDB_connection shows nothing,
Using var_dump on $connection shows "resource(9) of type (mysql link)"
Removing the $connection from the mysql_query has it connect to the
other DB (gameDB_connection) and I get an error that the table
doesn't exist (its not on that DB).
Adding / changing / removing the backquote ( ` ) from the query seems
to have no effect on the error
The variable $gID echo's correctly, so it's not null (its 1001 in
this case)
If I run the SELECT part in the actual sql form (instead of via php),
it lists them all correctly
The Connection.php is used in other places (one page reads
from both databases at the same time) successfully. No errors anywhere else
Anyone have any idea what's wrong?
Based on the comments, it sounds like the problem is caused by using require_once() inside a function.
One of two thing is happening. Either:
You've already included Connection.php somewhere else, so when you get to the function, it's not actually included.. because of the once part of require_once.
or...
It is working the first time you call the function, but the second time you call it, the file has already been included and does not get included again.
The problem is that when the file is first included (assuming that's from within this function), the $connection variable is created in the function scope, and like any other function variable, is gone at the end of the function. When you call the function a second time, the include doesn't happen because you're using require_once.
You could probably fix this by calling require() instead of require_once(), but that will end up reconnecting to the database every time you call the function - which is a lot of unnecessary overhead. It's much cleaner to just move the include outside of the function, and either pass the connection into the function, or use it as a global variable.
That would look like this:
require_once('Connection.php');
function getResult() {
global $connection;
$findQuery = "SELECT * FROM `Keys` WHERE `ID` = '$gID'";
$findResult = mysql_query($findQuery, $connection) or die(mysql_error());
$resultRow = mysql_fetch_assoc($findResult) or die(mysql_error());
}
All that being said, there's 2 major problems with this code.
You're using the mysql_* functions which are deprecated and will soon be removed from new versions of PHP. See this question for more details: Why shouldn't I use mysql_* functions in PHP?
It's not actually that hard to switch to something like the mysqli_* functions instead - there's a non-object set of functions that are almost identical to what you're using now.
You're including a variable in your query without properly escaping it. At the very least you should be calling mysql_real_escape_string() (or mysqli_real_escape_string()), but a better solution is to look into prepared statements. You can find more information on prepared statements here: How can I prevent SQL injection in PHP?

mysqli_stmt_prepare returns false from within a function

I am trying my best to object orientate my login scripts and checks for my website. As such, I have created a function that is called named "attempt_login". This function uses a database connection via the "mysqli_connect" function provided by a outside php file that is included and returns the $link variable.
However, when in my "attempt_login" the "mysqli_stmt_prepare" function is reached. It always returns false, and as such, the if statement never runs.
mysql_connect.php
require_once '../conf.php';
$link = mysqli_connect($mysql_server,$mysql_user,$mysql_pass,$mysql_db);
if(mysqli_connect_error())
{
//Fail
echo mysqli_connect_error();
}else{
//Success
}
return $link;
And the code from the "attempt_login" that fails:
$link = require_once 'functions/mysql/mysql_connect.php';
print_r($link);
$stmt = mysqli_stmt_init($link);
echo mysqli_stmt_error($stmt);
echo mysqli_error();
//This if statement always fails.
if(mysqli_stmt_prepare($stmt,"SELECT member_salt FROM members WHERE username=?" ) )
{
mysqli_stmt_bind_param($stmt,'s',$login_details['username']);
mysqli_stmt_execute($stmt);
$member_salt = NULL;
mysqli_stmt_bind_result($stmt,$member_salt);
mysqli_stmt_close($stmt);
}
And calling the function is pretty simple.
attempt_login($login_details);
I have tried many ways to do this, but it seems to only work when it is not within a function. Which defeats the purpose of me trying to have it in a function. If I move the error output to after the if statment, it will print:
No Database Selected
Even though one clearly is set in the link. I also can do a print_r($link); and it does print proper data for the mysql server.
It also has the same issue with procedural and object orientated mysqli styles, and fails as well with "mysqli_prepare".
I do have mysql working on the site, but any attempts to run anything within a function fails.
I have searched for several hours on trying to find a answer, but was unable to locate anything. I look forward to hearing from you! Many thanks in advance.
~Travis
I'd say then you haven't selected a database.
Either $mysql_db isn't set in ../conf.php or there is a typo or $mysql_db isn't visible in mysql_connect.php.
You don't seem to be passing $stmt to your function, I would advise your read this on scopes.

Database connections and functions?

I'm new to using functions, so - no judgements please ;).
Let's say I have a function add_to_x() in function.php which within performs a mysql_query(). This function is included, (include "function.php";), into script.php, and called mid-way through that script. At the top of function.php I establish a database connection, closing it at the end.
Would this be passed through by default to the function add_to_x() or would I need to establish and close a connection within add_to_x() itself?
For illustration and good measure:
Contents of script.php
include "function.php";
// Do something
add_to_x($arg1, $arg2);
// Do something else
Contents of function.php
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
function add_to_x($arg1, $arg2) {
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query);
}
mysql_close($conn);
Would that work? Or would I need to do something like this:
function add_to_x($arg1, $arg2) {
include "db_conn.php";
$conn = mysql_connect($db_host, $db_user, $db_pass); mysql_select_db($db_name);
// Do something
$query = "SELECT * FROM table WHERE x = '$arg1'";
$result = mysql_query($query)
mysql_close($conn);
}
It might look like a rather stupid question, but I'm not sure of the scope of connections/functions. I feel that perhaps the second example would be better practice even if the first would work?
Any comments, advice, answers would be greatly appreciated! (I realize I've made this question a bit messy, but I hope the illustration code helps, and of course, if you need further clarification please do ask for it)!
You can open the database connection in the file that defines your functions, as you are doing. But closing it at the end of function.php is not what you want to do - by doing this you are closing the connection before it is ever used.
You would either call mysql_close() at the very end of your main script (after all calls to functions that require the connection), or not at all (the resource will be implicitly closed/freed when the script finishes).
Any code that's in the global scope of function.php (ie not inside a function), will be executed when you include the script. So in the code you posted, the $conn will no longer be open in your add_to_x().
Few things to explain:
1) If you have $conn defined in global scope, you can access it from any function using keyword global e.g.
function add_to_x(){
global $conn;
}
2) you can use mysql queries in your functions even if connection is made "outside", as mysql will use last opened connector, unless other specified
summing up, first of your example should work (did not check parsing etc).

Categories