Another little bit which I am missing (as a beginner) I have a Backup script between two DB and as a final step I should optimise the real DB to reduce the size of the overhead. I have a code which works when I use only one DB but I need to use two:
$actconn = mysql_connect($dbhost, $actdbuser, $actdbpass) or die ('act Error connecting to mysql');
$bckconn = mysql_connect($dbhost, $bckdbuser, $bckdbpass) or die (' back Error connecting to mysql');
$ressql="SHOW TABLE STATUS FROM $actdbname WHERE Data_free / Data_length > 0.1 AND Data_free > 102400";
- this should tell that bckuser is ignored, I believe...
$res = mysql_query( $ressql, $actconn);
echo mysql_error();
while($optrow = mysql_fetch_assoc($res)) {
mysql_query('OPTIMIZE TABLE ' . $optrow['Name'], $actconn);
}
actconn value: Resource id #1
bckconn value: Resource id #2
mysql_error says:
SELECT command denied to user 'bckuser'#'localhost' for table 'actual table'
any idea what I do wrong?
UPDATE:
bckuser should not do anything with it as actdbuser is the root of that DB, but some reason SHOW TABLE won't recognise $actconn...
UPDATE2:
I tried just the opt again and the only thing is changed is the $actdbname='db-name'; when working and $actdbname='db-name' with the spec apostrophe;
please note this is on sharedhost so I can't change the DB name.
thanks #Corbin interesting idea, I tried and didn't work, but how could I debug it? I can't even debug it properly some reason...
You need to have a proper grant permissions to user 'bckuser'#'localhost' for executing SHOW TABLE STATUS query.
Unfortunately in MySQL 5.5 there is no separate grant option for this operation. Alternatively you can grant ALL to this user or use root user login for doing this operation.
see Grants Manual
Related
I usually connect php to mysql with localhost in my PC..
now i'm trying to put my project in cloud https://c9.io ,but i can't connect to mysql. i already have mysql database in cloud and put my project in same place...
mysql_connect("/lib/mysql/socket/mysql.sock","myUser","") or die(mysql_error());
i use script above to connect but i get Unknown MySQL server host '/lib/mysql/socket/mysql.sock' (1)
what shoul i do ?
Okay, so none of the above answers had worked for me, but fortunately I was able to setup a database and get it up and running my own way and I can now make queries and run them successfully, so I will share my method with you in hopes that anyone else scouring the internet can stumble across this and not have to go through the same head scratching that I did.
If you want the quick rundown, just scroll to Step 3 and read on from there. If you're a complete beginner, keep reading as I'll walk you through it in detail.
Couple things to mention:
You will have to setup a database via a Terminal in Cloud 9. I had no experience prior doing it in a Terminal before, but it's very simple to learn.
You can not use mysql functions, you have to use mysqli, since mysql functions are deprecated and Cloud 9 will not run them.
Step 1: Setup MySQL on Cloud 9 (in Terminal)
In your project, open up a New Terminal (click the plus-sign tab above the text editor space, select "New Terminal"). In the terminal, type mysql-ctl start and hit Enter. MySQL will start up in the back, but you won't get any response back in the terminal.
Next, type mysql-ctl cli and hit Enter. You should see some text that starts off as Welcome to the MySQL monitor.... Congrats, you've setup MySQL on your Cloud 9 project.
Step 2: Create a test database (in Terminal)
You can actually go ahead and create your official database if you like, but for this sake I'll just make a database that holds a table that holds an ID and a username. So here's the steps to setting up a database and a table. If you've used MySQL and databases before, then this should be cake, but I'll explain it in detail for those who might not fully understand MySQL .
Type SHOW DATABASES; and hit Enter. This will show a list of current databases within your project. You can enter this any time you want to see a list of your databases on the current project.
Type in CREATE DATABASE sample_db; and hit Enter. You should get a Query OK, 1 Row affected. which means the query was successful. You can name the database whatever you like, but for this little walk-through, I named it sample_db.
Type in USE sample_db; and hit Enter. This selects sample_db from the list of databases.
Type in CREATE TABLE users (id INT(11), username VARCHAR(20));, and hit Enter. This creates a table named users with two columns: id and username. The number in parentheses represents the character limit the column will store in the database. In this case for example, username won't hold a string longer than 20 characters in length.
Type in INSERT INTO users (id, username) VALUES (1, "graham12");, and hit Enter. This will add the id of 1 and a username graham12 in the table. Since the id column is an INT, we do not put quotes around it.
Type in SELECT * FROM users;, and hit Enter. This will show everything that is in the users table. The only entry in there should be what we inserted from the last step we just did.
Step 3: Get the credentials you'll need to connect to the database from PHP. (in Terminal)
Now we have some data in our table that we can test our mysqli connection with. But first, we have to get the credentials we will need to connect to the database in PHP. In Cloud 9, we will need 5 credentials to connect:
Host name
Username
Password
Database name
Port #
Username, password, database name, and port #, are practically already known to you by now. I'll explain:
Host name - Type in SHOW VARIABLES WHERE Variable_name = 'hostname';, and hit Enter. You'll get a table that has 2 columns: Variable_name and Value. In the Value column you should see something like yourUsername-yourProjectName-XXXXXXX, where the X's are a 7 digit number. Write this number down or save it some where. This is your host name. (If you're getting the quick rundown on this walkthrough, just start a new terminal and start up your mysql and select the database you want to use, then type in SHOW VARIABLES WHERE Variable_name = 'hostname';. Re-read this step from the beginning if you're confused.)
Username - Your username that you use to log in to Cloud 9.
Password - There is NO password for your database in Cloud 9.
Database name - This would be sample_db or whatever you named your database;
Port # - is 3306. In Cloud 9, all of your projects are wired to 3306. This is a universal constant of Cloud 9. It will not be anything else. Write this as you would an integer, not as a string. mysqli_connect() will interpret the port # as a long data type.
Last Step: Connect to the database with PHP! (using PHP)
Open up a PHP file and name it whatever you like.
I'll pretend that my host name is graham12-sample_db-1234567 for this example and that this is what my data looks like:
Host name: "graham12-sample_db-1234567"
Username: "graham12"
Password: ""
Database name: "sample_db"
Port #: 3306
So in PHP, insert your credentials accordingly:
<?php
//Connect to the database
$host = "grahamsutt12-sample_db-1234567"; //See Step 3 about how to get host name
$user = "grahamsutt12"; //Your Cloud 9 username
$pass = ""; //Remember, there is NO password!
$db = "sample_db"; //Your database name you want to connect to
$port = 3306; //The port #. It is always 3306
$connection = mysqli_connect($host, $user, $pass, $db, $port)or die(mysql_error());
//And now to perform a simple query to make sure it's working
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo "The ID is: " . $row['id'] . " and the Username is: " . $row['username'];
}
?>
If you get a result and no error then you have successfully setup a database and formed a connection to it with PHP in Cloud 9. You should now be able to make all the queries you can normally make.
Note: I demonstrated the last part without using parameterized queries for the sake of being simple. You should always use parameterized queries when working with real web applications. You can get more info on that here: MySQLi Prepared Statements.
For starters, the mysql_* functions are deprecated so you shouldn't be using them. Look at PDO or mysqli instead. Next, you'll want to try this per the example docs:
$link = mysql_connect('localhost:/lib/mysql/socket/mysql.sock', 'myUser', '') or die(mysql_error());
To find the ip running you project, create a test file with the code below, run it and put the result as host.
<?php
$ip = getenv("REMOTE_ADDR") ;
Echo "Your IP is " . $ip;
?>
You are using Cloud9 so it's a little different to use. To connect to MySQL you have to first create the MySQL server in C9. Type this in C9's command line:
mysql-ctl start
C9 will create your mysql server.
MySQL 5.1 database added. Please make note of these credentials:
Root User: <username>
Database Name: c9
Next to find your IP address type:
echo $IP
Now use this code with your username, the ip address, no password and the 'c9' database to access MySQL:
mysql_connect("<$IP>","<username>","") or die(mysql_error());
mysql_select_db("c9")
Hope this helps
The documentation show how start, stop, and run the mysql environment.
Start the MySQL shell mysql-ctl start then in yor file.php:
$ip = getenv("REMOTE_ADDR");
$port = "3306";
$user = "YorUsername";
$DB = "c9";
$conn = mysql_connect('$ip', '$user', '', '$db', '$port')or die(mysql_error());
mysql_select_db('$db','$conn')or die(mysql_error());
mysql_query("select * from YourTableName",'$conn')or die(mysql_error());
The line getenv("REMOTE_ADDR") return the same local IP as the application you run on Cloud9.
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'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...
I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');
I have been learning how to program websites lately and the time has come for me to add a database. I have in fact already successfully created a MySQL database and interacted with it with PHP.
My problem is I can't seem to access a SQLite database file with it. I am using MAMP to host locally for now. Here is a snippet of the code I am using to access the db and find and print out a value stored on it.
<?php
$dbhandle = sqlite_open('/Applications/MAMP/db/sqlite/Users');
if ($dbhandle == false) die ('Unable to open database');
$dbquery = "SELECT * FROM usernames WHERE username=trevor";
$dbresult = sqlite_query($dbhandle, $dbquery);
echo sqlite_fetch_single($dbresult);
sqlite_close($dbhandle);
?>
As you have access to the database (your code doesn't die), I'd say there's got to be an error later ;-)
Looking at your SQL query, I see this :
SELECT * FROM usernames WHERE username=trevor
Are you sure you don't need to put quotes arround that string ?
Like this :
SELECT * FROM usernames WHERE username='trevor'
Also, notice that sqlite_fetch_single will only fetch the first row of your data -- which means you might need to use sqlite_fetch_array or sqlite_fetch_object if you want to access all the fields of your resulset.