This is the code that connects to my SQL database. I'm new with this stuff and it seems to be semi-working but certain features on my website still don't work.
<?php
$con = mysql_connect("localhost","username","password");
$select_db = mysql_select_db('database1',$con);
/*$con = mysql_connect("localhost","username2","password2");
$select_db = mysql_select_db('database2',$con);*/
?>
This is the site in question: http://tmatube.com keep in mind the credentials above are filled in with what the programmer used for testing on his own server... ;) unfortunately I don't have access to him for support anymore.
Anyway, here's my thoughts on how this code needs to be edited maybe someone can chime in and let me know if I'm correct in my assumptions:
<?php
$con = mysql_connect("localhost","username1","password1"); -------------<<< leave this line
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);
/*$con = mysql_connect("localhost","DB_USERNAME_HERE","DB_PASSWORD_HERE");
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con);*/
?>
Ok - now on to a few problems I noticed...
What does this do? /* code here */? It doesn't work at all if I leave that bit in.
Why is it connecting to database twice? and is it two separate databases?
$select_db = mysql_select_db('DATABASE_NAME_HERE',$con); <<<---- single '
When I tried to see if that line was correct the examples I saw had quotes like this
$select_db = mysql_select_db("DATABASE_NAME_HERE",$con); <<<---- double "
Which one is right?
He didn't leave it out. What he did was leave the database to be connected using the root, which has no password. The other connection (which is commented out) is using another user, rajvivya_video, with a password defined.
In testing it MIGHT be okay to connect to root and leave it without password, but even that is not recommended, since its so easy to work with a user and password defined (besides root).
Here is php mysql connect with mysqli:
<?php
$link = mysqli_connect("myhost","myuser","mypassw","mybd");
?>
No difference here with ' or ". (Anyway use mysqli and you can the wanted db as 4th parameter.) php quotes
/* comment */ is a commented out so the php does not care what is inside so only 2 first rows of are affecting (they are same mysql database on the local machine and 2 different user + password combinations). Comment in general are used to explain the code or removing part of the code with out erasing it. php commenting
Related
I've encapsulated my MySQLi connection logic in a script named connect_mysqli.php. This working just fine all over my project (9 other pages are having no trouble), but one page is returning this error:
Warning: mysqli::query(): Couldn't fetch mysqli in C:\xampp\htdocs\projectName\php_calls\AddItem.php on line 193
Here's the code that's not working in AddItem.php:
$sql = <<<HEREDOC
UPDATE listing_data
SET ebay_id = '$responseObj->ItemID'
WHERE listing_id = '$database_listing_id'
HEREDOC;
require_once(__DIR__ . '/connect_mysqli.php'); //this creates $conn
$conn->query($sql); //this is line 193
And this is the code from connect_mysqli.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$db = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->set_charset("utf8");
Again, this is working without trouble in every other spot in the project. Here's what I've tried so far:
I checked my SQL syntax. I echoed the SQL query I'm attempting and tested it on the command line, the query is working fine.
Double check my SQL again. I copied the code from a working database call into the AddItem.php. It produces the same error. I tested the original page where this code exists, it works correctly in that spot.
I checked to make sure require_once is working correctly. To make sure my relative path was working correctly, and I am in the cwd that I expected I was in:
echo require_once(__DIR__ . '/connect_mysqli.php');
and it produced:
C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This was expected. I opened Windows Power Shell and ran:
cat C:\xampp\htdocs\projectName\php_calls/connect_mysqli.php
This displays the code inside connect_mysqli.php! I was beginning to guess my require_once was flawed.
Check to see if there's a naming collision.
var_dump(get_defined_vars());
There is only one $conn.
The connection is not being closed with $conn->close();. If it's closing without my instruction I don't know how or why.
I copied and pasted the code from connect_mysqli.php into AddItem.php and the error goes away. So somehow my require_once must be messing up my connection. AddItem.php and connect_mysqli.php are in the same folder. I tried connecting with this line instead:
require_once('connect_mysqli.php');
I still get an error.
Sorry for the incredibly lengthy question, I wanted to do my research and try everything before creating another question on the topic. For now I can copy the database connection code into AddItem as a workaround, but it's bad practice, and there's clearly some important principle escaping me here that I'd like to understand.
Edit: more information
Nico Haase asked the question that put me on the right track. Line 1 of AddItem.php is a require_once:
require_once(__DIR__ . '\return_item_php_obj_by_id.php');
and inside return_item_php_obj_by_id.php we have the culprit:
require_once(__DIR__ . '/connect_mysqli.php');
//edited out irrelevant code
mysqli_close($conn);
In the original post I said "There's no $conn->close() hiding anywhere." Clearly I was mistaken. I found the hidden close(). When I comment this out, the connection works. Now I've accidentally made my code really hard to read, and I don't want to use a database connection that far away on the stack. Should I leave the connection open so I can use it again with AddItem.php? What's best practice in this case?
I have a small problem. I'm trying to make a simple register/login system with sessions and I got this error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\members\includes\login.inc.php on line 9
This is the relevant line of code:
$result = $conn->query($sql);
The first time I tried it was working.
The rest of the code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$email = $_POST['email'];
$password = md5($_POST['password']);
$sql = "SELECT email, password FROM member WHERE email = '$email' AND password = '$password'";
$result = $conn->query($sql);
I also have db.php, which is used to connect the MYSQL and everything inside it is fine.
I cannot understand why, the first time I tried it was working I guess and now this kind of error.
I'm also having the db.php which is used to connect the MYSQL and everything inside is fine.. could someone explain me why I keep facing this error ?
I'm going to speculate. I'm speculating that you have a separate file (probably called db.php) which "handles" the setting up of the database connection. I'm further going to speculate that you've a chain of files which are require() (or include())'d into your web app.
I've seen this more times than I care to recall. It's a very old fashioned way of separating code into logical chunks inside PHP - which needs to be left in the past.
I'm speculating that you were previously defining $conn in another script which was included (or required) before this code. A global variable, which had was dependency later in the code execution. Invisible to the file it was declared in.
That's the problem. The quick/hack fix is to rename $conn or the restore the original declaration of it and make sure it's global and make sure it is included before this code is ran.
The proper fix (IMHO) is to look at using a framework (Laravel, Lumen, CodeIgniter, Yii, there are many - take your pick) and read up on the topics of dependency injection, autoloading and namespacing. Think about why global variable declarations make for unmaintainable code.
If you're really reluctant to go with a full framework, at the very least have a look at some database-abstraction libraries like doctrine (and it's sub-library dbal) which can easily be auto-loaded into your project via composer.
As Sascha already pointed out, $conn might be either not defined at all, or it's not an object (hence the error message).
From the code sample you have provided, it's actually a bit hard to tell what kind of connection object you might be using, but I think it's save to say that in your case it might be either PDO or mysqli.
For the sake of simplicity, let's stick with mysqli. A working code sample based on mysqli would look like this (shortened example taken from the docs cited above):
$conn = new mysqli("localhost", "my_user", "my_password", "world");
$result = $conn->query($sql);
Though you really should go for so-called prepared statements, as your code right now is prone to SQL injection as wally already stated.
I would have linked wally's answer and provide you with a link to the PHP docs relating to prepared statements, but apparently, my lack of reputation points don't allow me to, so just do a quick Google search for PHP & prepared statements.
The database connection file has to be added at the beginning of the file.
The present format is easy.
<?php $mysqli = new mysqli("localhost", "Userid", "password", "database name"); if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; }
?>
At the beginningļ¼
require 'db.php';
$conn = new db();
I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.
I have a PHP function that any other function on my server goes to to connect to a global MySQL database:
function connect_to_mysql_db() {
$con = mysql_connect("localhost", "user_name", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db_name", $con);
}
The file which holds this function, as well as most of the others, is located in the following location on my BlueHost server:
/home3/username/includes/scripts.php
The database currently holds only one table with a list of email addresses (those of my subscribers...) I just want to know if the database is secure (for the sake of my subscribers)
If not, does anyone have any other ideas (encryption?). I know HASHING won't work because that is usually 1-way...
EDIT
FYI: The /includes/ directory is not /public_html/
CONCLUSION
Thank you to all who helped me, but I decided that there is just too much liabilities for no good reason, so I will not be storing anything secure in a database. Instead, I will use external services!
Cheers!
I don't think this will give you any additional security.
If someone hacks your server, reads the scripts to get the database credentials, logs into mysql, reads the mailadressen and gets only encrypted data, he will probably take a second look into the scripts for the decryption key...
So, I think this is not going to make it way more secure. You better focus on writing a secure environment to prevent any access to the server ;-)
I think it's secure enough. Anyway if you want more, try something like this:
$crypted = openssl_encrypt ('myemail' ,'AES256', 'mypass')
and then
$decrypted = openssl_decrypt ($crypted, 'AES256', 'mypass')
Reference here.
You could AES encrypt the email addresses.
ie:
$query = "INSERT INTO (table) AES_ENCRYPT('$email', '$salt')..."
To get the email back in normal text:
$query = "SELECT AES_DECRYPT('email', '$salt') FROM (table) WHERE 1..."
$salt would be a randomly generated key that you put into the variable.
The column in you database table needs to be a blob.
Just to get started, and thinking I needed a "database," I did this:
$db = new PDO("java:comp/env/jdbc/mysql");
$stmt = $db->query("CREATE DATABASE kitty_db");
To see if it worked I commented out the above and then wrote:
$link = mysql_connect('localhost:3306', 'me', 'blah');
$db_list = mysql_list_dbs($link);
while($row = mysql_fetch_object($db_list)) {
echo $row->Database ."<BR>";
And I saw that my new database was there:
information_schema
mysql
kitty_db
performance_schema
test
And so my first question is, did I even need to make a new database next to mysql just to get started on something? I don't recall ever having to do that a couple of years ago (7 actually) when I was setting up MySQL before (sans via PHP).
Anyway, I'm wondering why I can't create a table now. If kitty_db isn't a good idea, let's take it out. But I may be having trouble putting a TABLE 'milk_bowl' (with an index or key or whatever 'bowl_name' field).
Thanks for any help. Things have gotten more complex since I just opened up a command line in MySQL almost a decade ago and just issued simplistic queries.
And so my first question is, did I
even need to make a new database next
to mysql just to get started on
something? I don't recall ever having
to do that a couple of years ago (7
actually) when I was setting up MySQL
before (sans via PHP).
This question is kind of vague. You are asking about needing to make a database to start on something? Without know more about your something, I don't really think that question is answerable. Creating the database is usually the first step when setting up a database. You might find this helpful when getting started.
Anyway, I'm wondering why I can't
create a table now. If kitty_db isn't
a good idea, let's take it out. But I
may be having trouble putting a TABLE
'milk_bowl' (with an index or key or
whatever 'bowl_name' field).
From the above link (adapted to your example):
<?php
$con = mysql_connect("localhost:3306","me","blah");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Create database
if (mysql_query("CREATE DATABASE kitty_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
// Create table
mysql_select_db("kitty_db", $con);
$sql = "CREATE TABLE milk_bowl
(
bowl_name varchar(15),
)";
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
Thanks for any help. Things have
gotten more complex since I just
opened up a command line in MySQL
almost a decade ago and just issued
simplistic queries.
I don't think that's changed all that much. You can still use the command line to connect to your mysql db and issue queries directly. PHP just lets you do it through a browser/scripts.
This is not a direct answer to your question, but it might solve your problem... have you tried using an application such as MySQL Administrator or MySQL Query Browser? I came back to MySQL recently after a very long hiatus as well and found them both very helpful.