How to specify a database in a query in MySQL? - php

I am writing a PHP script to log in to a website. Right now, I am making a "My Profile" page, where all you info, like Username and Email are displayed. I have MySQL set up. In MySQL, a database named registeredusers holds all the info like username, password, and email. I can use PHPMyAdmin to view it, but I must first select the database registeredusers to run a query on it. This is the command I am trying to run.
SELECT username FROM users WHERE id = 1
My table inside registeredusers database is called users. The username value is username. Id is just an incrementing number I use to identify each different account.
I want to be able to run this in the global query box. What would I have to change in the code to select registeredusers as the database I want to run it on?

If using mysqli:
$mysqli = new mysqli("localhost", "root", "root", "registeredusers");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Here is some more information on that http://php.net/manual/en/mysqli.quickstart.connections.php
If you are using PDO (PHP5), you can use the following code which was taken from here (http://php.net/manual/en/class.pdostatement.php):
$host = "yourHost";
$user = "yourUser";
$pass = "yourPass";
$db = "yourDB";
$cursor = "cr_123456";
try
{
$dbh = new PDO("pgsql:host=$host;port=5432;dbname=$db;user=$user;password=$pass");
echo "Connected<p>";
}
catch (Exception $e)
{
echo "Unable to connect: " . $e->getMessage() ."<p>";
}

Related

How can I get mysql to print rows from a database table

I am trying to learn php from W3schools which includes a mysql section.So far I have completed every other part of the tutorial on w3school except the part that prints content from a database table. For some very weird reason , nothing displays when I run my code. Please how can I get this working and could my problem come from the fact that I am using MariaDB with Xampp instead of Mysql although they said it was practically the same syntax.
Here is the code
<?php
$servername = "localhost";
$username = "uhexos";
$password = "strongpassword";
$database = "fruitdb";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE fruitDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);
// sql to create table
$complexquery = "CREATE TABLE MyFruits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FruitType VARCHAR(30) NOT NULL,
FruitTaste VARCHAR(30) NOT NULL,
FruitQuantity INT NOT NULL,
DatePurchased TIMESTAMP
)";
if ($conn->query($complexquery) === TRUE) {
echo "Table Fruits created successfully<br> ";
} else {
echo "Error creating table: " . $conn->error;
}
$entry = "INSERT INTO myfruits (fruittype,fruittaste,fruitquantity) VALUES ('orange','sweet','50'),('lemon','sour','10'),('banana','sweet','15')";
if ($conn->query($entry) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $conn->error;
}
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['fruitname']} <br> ".
"EMP SALARY : {$row['fruittaste']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
this is the output I get from all my echos.
Error creating database: Can't create database 'fruitdb'; database existsError creating table: Table 'myfruits' already existsNew records created successfully
or
Database created successfullyTable Fruits created successfully
New records created successfully
Based on the error message, you managed to create the database and tables once and now each time you run the code it fails because you can't reuse the names.
You definitely don't want to have code trying to erase & start fresh on your database every time. In fact, most often I find that you don't even create the database inside your regular code but use phpMyAdmin or some other admin page to do that. But creating tables inside code is normal enough. Two options:
1 - Create the table only if it does not already exist. This is extremely safe. However, if you want to start a table over again with a new structure, or start with it always empty, that won't work. To do that, just change CREATE TABLE to CREATE TABLE IF NOT EXISTS
2 - Delete the table before creating it. Before each CREATE TABLE command, add a command like DELETE TABLE IF EXISTS MyFruits
Remember database name is Case-insensitive, so it doesn't matter whether you create a DB name "fruitdb" or "fruitDb" both are same.That is the reason you are getting error. Also you don't have to create a new database when you execute any file. If you have already created the database than you only have make the connection with it.
Let's debug your code line by line.
Line 8 -
// Create connection
$conn = new mysqli($servername, $username, $password);
Here you are creating the connection with your database because you have already created that database. If you check your phpmyadmin, you'll find a database named "fruitdb"
Line 10 -
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Here your checking whether the you are able to connect with your database. If not it will throw the error and your script will stop. Right now your code successfully runs till this point.
Line 15 -
// Create database
$sql = "CREATE DATABASE fruitDB";
Here you are again creating a database with same name and your code stops working as you already have it.
The error was from this line
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
I accidentally put fruitname instead of fruittype and that is what caused it to fail. So for anyone else with thi problem my advice is to check your variable names if you are 100% sure of your syntax. Thanks for all the help.

How to connect to a new database using PHP MySQL

So I've been trying to learn how to use MySQL with PHP, and I've managed to create a connection and create a database along with a table. What I don't know how to do is create the database along with the tables all in one go.
What I mean by this is easier shown in my code (Which will show unable to connect error message because the connect method is trying to connect to a database that does not exist.
<?php
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
So, all I am trying to achieve is Connect to MySQL, create the database, create a table for said database and close the connection all within one .php file.
On a side note, due to the user being able to define a database name ($dbname), how would I add this value into the MySQL code above? I heard somewhere that you're supposed to add the variable into quotes? So '$dbname'. Any help with that would be good too! Thanks in advance!
Okay, the reason for this question is because I am creating a setup-type page where the user will be able to connect to their own database, allowing them to give it a name and connect using their credentials. Obviously I am not very experienced within this field, I hope I have explained it better.
All the code you have looks fine to me. The only thing I think your missing is after you create a database you have to call
$conn->select_db("myDB");
Also if you want to have the database name be $dbname then
$sql = "CREATE DATABASE myDB";
should be
$sql = "CREATE DATABASE " . $dbname;
If I didn't cover your problem please give me more detail on your problem.
where you passing all of this variable ?
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
just simply hardcode the servername, username, password and your dbname.

MySQL query fails silently in php

This is my PHP code written for website. When I executed this, the query doesn't execute and doesn't show any error. I also checked data types of values that are to be inserted.
The database username and password and all credentials are correct. What could be the problem?
<?php
$password ='abcdef';
$host="localhost"; // Host name
$username="futureti_dsatya"; // Mysql username
$password="D2e3e4v1i"; // Mysql password
$db_name="futureti_db"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
$con = mysqli_connect($host, $username, $password,$db_name);
if(!$con)
{
die('Could not connect: '. mysql_error());
}
else
{
$res = mysqli_query($con,"insert into users values(55555623,'saran1','satya_saran',$password)");
if($res){
print("i am ok");
}
else{
print("bad");
}
}
?>
Wrap $pass in quotes (55555623,'saran1','satya_saran','$pass') as shown below with an explanation about "$password", and change mysql_error()); to mysqli_error()); those two functions don't mix and that is why you did not get the proper error messages to show up.
As already stated, you're using $password twice; change one of the variables to something else.
What you're presently doing is overwriting your $password variable.
I am assuming you want to enter abcdef into your DB. If so, then do this instead:
<?php
$pass ='abcdef';
$host = "localhost"; // Host name
$username = "futureti_dsatya"; // Mysql username
$password = "D2e3e4v1i"; // Mysql password
$db_name = "futureti_db"; // Database name
$tbl_name = "users"; // Table name
// Connect to server and select databse.
$con = mysqli_connect($host, $username, $password,$db_name);
if ( !$con ) {
die('Could not connect: '. mysqli_error());
} else {
$res = mysqli_query($con, "insert into users values (55555623,'saran1','satya_saran','$pass' )");
if( $res ) {
print("i am ok");
} else {
print("bad");
}
}
?>
Also, inserting data into a table without telling it which columns to use is not a recommended method.
Use something to the effect of:
($con, "insert into users (column1, column2, column3, column4) values (55555623,'saran1','satya_saran','$pass' )
Sidenote: If the column for your first value isn't an (int) you will need to wrap that in quotes as well.
Also, if your first column is an AUTO_INCREMENT, you will need to remove the AUTO_INCREMENT from the column's type.
you dont get any error because you are making using mysql. not mysqli.
your code is wroking just wrap password . i guess the connection is not connecting.
replace this:
die('Could not connect: '. mysql_error());
to
die('Could not connect: '. mysqli_error()); //to see the error

PHP MySQL - Error: No Database selected

I am trying to read and write to a database. Here is the code I have so far:
$mysql = mysqli_connect("example.com", "johndoe", "abc123"); // replace with actual credidentials
$sql = "CREATE DATABASE IF NOT EXISTS dbname";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($mysql);
$mysql = mysqli_connect("example.com", "johndoe", "abc123", "dbname"); // replace with actual credidentials
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
$sql = "INSERT INTO Customers(username, password, email) VALUES(" . $username . ", " . $password . ", " . $email . ")";
if (!mysqli_query($mysql, $sql)) {
echo "Error: " . mysqli_error($mysql);
}
mysqli_close($mysql);
However, when I try to run it, it has an error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , )' at line 1
Could anybody tell me how to fix this?
Please check syntax of mysqli, it takes 4 parameters.You also have to provide database name.
$link = mysqli_connect("myhost","myuser","mypassw","my_db");
You're missing database in mysqli_connect() call
$link = mysqli_connect("hostname","username","password","database") or die("Error " . mysqli_error($link));
Obviously the answer is in your error. You didn't select any database. When using this function mysqli_connect specify the database you want to connect to.
Here is the syntax of the function: http://www.w3schools.com/Php/func_mysqli_connect.asp .
1) Create your database outside of your application
2) Specify mysqli_connect with the database you want to select.
You can also use another function called mysqli_select_db . You can find the sytanx here : http://www.w3schools.com/php/func_mysqli_select_db.asp .
As already stated in the comment, you will also have to replace : "example.com" with your ip address, if you are running locally replace it with 127.0.0.1:3306 , if you didn't change the port when you installed your mysql database / "johndoe" with your database account, you can change that to "root" / "abc123" with your root account password DEFAULT : "" .
Good luck !
First check mysqli_select_db if it returns false then create database.
try like this:
$mysql = mysqli_connect("example.com", "johndoe", "abc123") or die(mysqli_connect_error()); // replace with actual credidentials
if (!mysqli_select_db($mysql,'hardestgame_accounts')) {
$sql = "CREATE DATABASE IF NOT EXISTS hardestgame_accounts";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating database: " . mysqli_error($mysql);
}
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "CREATE TABLE IF NOT EXISTS Users(ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(ID), username CHAR(15), password CHAR(15), email CHAR(50))";
if (!mysqli_query($mysql, $sql)) {
echo "Error creating table: " . mysqli_error($mysql);
}
mysqli_close($mysql);
here is a good answer: Php mysql create database if not exists
Try using mysql_select_db in between the database connection and the table creation.
Also, mysql_ is deprecated, please use mysqli_ instead
Use ` backticks for MYSQL reserved words...
your table name is reserved word for MYSQL...
Change your table name.

I need to use an SQL query to return results for the logged in user of my website

I created a module that will allow my users to view only the categories of blogs that they have selected. I am using an SQL query to access their data from mysqli. The code that I have is working as far as it is properly connecting to mysqli, but it is returning the blog category for everyone, even the users that have not selected the blog category.
How do I specify this code to only access the data from the specific user that is logged into their homepage.
<?php
$con = mysqli_connect("*****", "****", "*****", "******");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
jimport( 'joomla.application.module.helper' );
$moduleart = JModuleHelper::getModule('arraarticles', 'ArtsARRA');
$sqlarts = mysqli_query ($con, "SELECT * FROM jos_social_fields_data WHERE data LIKE '%MINIARTS%'");
if ($row = mysqli_fetch_assoc($sqlarts));
else {
echo JModuleHelper::renderModule($moduleart);
}
mysqli_close($con);
?>
To get the current logged-in user information, use the $user = JFactory::getUser(); method. More info here - http://docs.joomla.org/Accessing_the_current_user_object

Categories