mysql_select_db fail on somepage - php

I am making a social website for my company. The problem appears only in "diary" page. Most of time, my code connects to database successful, but sometime, it throws error:
Could not select database
This is my php code to connect to database on localhost:
function execute_action($query)
{
$link = mysql_connect("localhost", "root", "123456") or
die("Could not connect");
mysql_select_db("2t") or die("Could not select database");
$query = $query;
$result = mysql_query($query) or die("Query failed");
return $result ;
}
Do you have any solution to help me. Thanks for reading.

As you arent closing your database connections between querys, so, my first thought would be is you're reaching a max connection barrier to the mySQL server.
While this may not be the answer - showing the mysql_error would help.
As someone else pointed out, theres no need to connect and drop each time. Unless your page has incredibly long processing time, connecting at the start, closing at the end should be enough.

You need to pass the dbconfiguration $link while selecting the db and executing the query
mysql_select_db("2t", $link)
even in mysql_query( $query, $link)

Related

MySQL Log-In with PHP - How often?

Okay this might be an obvious question, but as soon as i call MySQL with PHP (whhich means i log in) and then close the PHP tag, (shown below) Do I have to call the database again later?
$mysqli = new mysqli("host", "username", "pw", "dbname");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT EmbedURL FROM Videos ORDER BY RAND() LIMIT 8");
etc...
And then I need to call it again later in the script to fetch something else fromt he database. Do i have to log into the database again?
Thank you!
The database connection will stay open if you do not close it manually. The only possible cause I can imagine that you could loose the connection is the connection timed out or was closed by the databse because you have to many active connections.
It looks like the database variable is nested deeply in your code. You will also loose the reference of the connection if you close the current code block (}).
Here is a post about MySQL connection pooling which could be insteresting for your problem: Connection pooling in PHP

PHP: could not find database

i am having difficulty with connecting my database to mysql, i have tried many different ways of trying to get it to connect to my database, but none these methods seem to work. I am only new to php and i could be missing something, but i dont know what it is.
This is for a search engine, i have the form created.
I would think that my problem is coming from this line of code, mysql_connect("localhost", "root", "") or die("could not connect");?!
I was wondering if i could be told what is the problem and how to fix it, thank you so much.
here is my code below.
<?php
//connect
mysql_connect("localhost", "root", "") or die("could not connect");
mysql_select_db("search") or die("could not find database");
$output = '';
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","", $searchq);
$query = mysql_query("SELECT * FROM gp management system WHERE Title LIKE '%$searchq%' OR Description LIKE '%$searchq%' OR Keyword LIKE '%$searchq%'") or die("could not search");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
}
else{
while($row = mysql_fetch_array($query)) {
$Title = $row['Title'];
$Description = $row['Description'];
$Keyword = $row['Keyword'];
$output .= '<div> ' .$Keyword. ' </div> ';
}
}
}
?>
SQL errors:
SELECT * FROM gp management system WHERE Title...
^^-- table name
^^^^^^^^^^ aliasing 'gp' as 'management'
^^^^^^-- extra unknown garbage
Table names shouldn't have spaces to begin with, but if you insist on having them, then you need proper quoting:
SELECT * FROM `gp management system` etc...
^--------------------^
Never output a fixed/useless "could not search" error. Have the DB tell you what went wrong:
$result = mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^^
As your only new, you really should stop using mysql_ and change to mysqli_ or (my preference) PDO(). Your message in your title seems to be coming from your selectdb line, so you're actually connecting to the database fine, it's just not able to locate the schema that you are trying to use (i.e. "search" does not exist as a schema name in your DB environment). Unless that's not the error that you are getting, in which case it's a flaw in your actual SQL query. Without an accurate statement of what you are getting back on the screen when you try to run the script then not much can be done to help.
I would rather do somehow like I did ages ago, see below:
function db_connect($host, $username, $passwd, $db_name) {
$db = mysql_connect($host, $username, $passwd);
if (!$db) {
echo "Login to database failed: ";
echo mysql_error();
return false;
}
$result=mysql_select_db($db_name); //Select the database
if (!$result) {
echo "Cannot find the database: ".$db_name;
echo mysql_error();
return false;
}
return $db; //Database descriptor
}
However you shouldnt rely on the old MYSQL extension, but use MYSQLi.
EDIT: as #tadman pointed out there were a # sign infront the mysql_connect call, however there is an if statement for checking and a call to error output.
As others have said, your code is something of a mess - you seem to be new to programming, not just in PHP. But everyone has to start somewhere, so....
You might want to start by learning a bit about how to ask questions - specifically you have included a lot of code which is not relevant to the problem you are asking about - which is about connecting to MySQL. OTOH you have omitted lots of important information like the operating system this is running on and what diagnostics you have attempted. See here for a better (though far from exemplary example).
Do read your question carefully - the title implies an issue with mysql_select_db() while in the body of the content you say you think the problerm is with mysql_connect(). If you had provided the actual output of the script we would have been able to tell for ourselves.
You should be checking that MySQL is actually running - how you do that depends on your OS. You should try connecting using a different client (the mysql command line client, sqldeveloper, Tora, PHPMyAdmin....there are lots to choose from).
You should also check (again this is operating system specific) that your MySQL instance is running on the same port as is configured in your php.ini (or overridden in your mysql_connect() call).
MySQL treats 'localhost' as something different from 127.0.0.1 on Unix/Linux systems. If this applies to you try 127.0.0.1 in place of localhost.
or die("could not connect");
Does not help in diagnosing the problem. If instead you...
or die(mysql_error());
You will get a more meaningful response.
BTW: while writing code using the mysql extension rather than mysqli or PDO is forgivable, I am somewhat alarmed to see what appears to be medical information managed with no real security.

Mysqli_error() does not work

The following code:
$dbc = mysqli_connect("localhost","root","root","magnificantDatabase")
or die("Could not connect to database");
$sql = "INSERT INTO accounts(username, password, ip)
VALUES('$username','$password','$ip')";
mysqli_query($dbc, $sql)
or die(mysqli_error($dbc));
Should return an error when the mysqli_query fails return an error, shouldn't it?
It doesn't though :/
Anyone have any ideas why it doesn't?
Oh and, by returning no error I mean it returns nothing at all.
just completely blank.
Edit: I'd like to let you know that after having searched the web (even though as this would seem a common problem) I have -NOT- found anything that fixes this, there are issues close to this one, but none of them I have found appear to be the exact same.
Same thing happened to me when I executed an UPDATE statement.
mysqli_error, mysqli_errno and mysqli_error_list were all empty.
Then I discovered that the problem was that the database user assigned to the connection object did not have the UPDATE privilege. I don't know why I did not receive an error message or an error number for this security/privilege breach.
Try to this..
$dbnm = "magnificantDatabase";
$abc= mysqli_connect("localhost","root","root") or die ("could not connect to mysql");
mysqli_select_db($abc,$dbnm) or die ("no database");
$sql = "INSERT INTO accounts(username, password, ip) VALUES('$username','$password','$ip')";
mysqli_query($dbc, $sql) or die(mysqli_error($dbc));

Delete row from MySQL not working

I'm trying to delete a row from a table in MySQL using the PHP code below. The return value from mysql_affected_rows() is 1. There are no errors. However, the row still exits in MySQL. Not sure what I'm doing wrong. Any thoughts?
$db = array('host'=>'127.0.0.1',
'user'=>'root',
'pass'=>'',
'name'=>'testdb');
// CONNECT TO THE MYSQL SERVER
$connection = mysql_connect($db['host'], $db['user'], $db['pass']);
if(!$connection){
// HANDLE ERROR HERE
die('Unable to connect to MySql server : '.mysql_error($connection));
}
// SELECT THE DATABASE SCHEMA
if(!mysql_select_db($db['name'],$connection)){
// HANDLE ERRORS HERE
die('Unable to connect to database : '.mysql_error($connection));
}
$result = mysql_query("delete from photos where id=".$photo_id, $connection);
echo mysql_affected_rows($connection);
UPDATE
I added the following code to the end and that solved the issue -
mysql_query("commit", $connection);
Thanks for the comments!
Applied to innodb tables as in your case.
mysql_query("BEGIN", $connection);
// delete code
mysql_query("COMMIT", $connection);
What I typically do in this cases is to enable the general_log (set global general_log_file=general.log; and set global general_log=1;) and look what arrives in there.
Then it often becomes already obvious what is the problem.
If it is not clear yet what is going on you can run these queries on the mysql console...

Correct Procedure for mysqlConnect

I am new to php syntax and am looking for advice on creating the most acceptable or correct code. I focus on front end design, but I like to make sure my code is proper. I am in a digital media program, my instructor has given us this code for connecting to our MYSQL databases.
<?php
mysql_connect("localhost", "root", "root")or die("Cannot Connect to DB");
mysql_select_db("Example")or die("cannot select the DB Example ");
?>
However when I look at connect scripts online they set the mysql_connect function as a variable lets say $connect and run an if statement stating; if not $connect produce error, and the same for mysql_select_db. They also close the script with mysql_close($connect); like below
<?php
$connect = mysql_connect("localhost", "root", "root");
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("Example", $connect);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
mysql_close($connect);
?>
Is either one better? What problems can I have if I dont close the connect with mysql_close?
Regarding using an if instead of an or, it doesn't matter. The or short-circuits, so if the connection worked, die(...) won't be executed. Using either is a matter of preference. If you want to use the or version while keeping the result of the mysql_connect() call, simply assign the whole expression to a variable:
$connection = mysql_connect(...) or die('Connection failed.');
mysql_close() should be used after you're done with all your database communication.
The other mysql_*() functions will use the connection created by the latest call to mysql_connect() or mysql_pconnect(). If for some reason you want more than one connection, trusting the implicit connection object in this manner will fail. Better is to store the connection object yourself and passing it in wherever you need it.
Also before starting to work with databases, you should be aware that mysql is not secure anymore and is deprecated, you should use mysqli. You can use it also as object oriented language.
more details : http://www.php.net/manual/en/book.mysqli.php
example :
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories