I am trying to learn php and mysql. So i tried making a database using phpmyadmin and connect it with my php.
Here is a simple example where I try to see if the database is working
<?php
$connection = mysql_connect("localhost","root");
if(!$connection) {
die("Database connection failed: " . mysql_error());
$db_select = mysql_select_db("nameofdatabase",$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
?>
<html>
<head>
<title>Databases</title>
</head>
<body>
<?php
$result = mysql_query("SELECT * FROM nameofdatabasetable", $connection);
if (!$result) {
die("Database query failed::: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[1];
}
?>
</body>
</html>
<?php
mysql_close($connection);
?>
and i get
Database query failed::: No database selected
which means than this part of code
<?php
$result = mysql_query("SELECT * FROM users", $connection);
if (!$result) {
die("Database query failed::: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[1];
}
?>
is not working (i put a different number of these ":" in each if.
Any help would be appreciated! Thank you!
The logic for your code doesn't make sense because if the connection doesn't happen then you would not be able to select a database and your database select statement is within the logic for if you cannot connect to the database. Try this instead:
$connection = mysql_connect("localhost","root");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db("nameofdatabase",$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}
I have to pass the username and password in the mysql_connect call. Here is my database open() function.
$this->con_error = "";
$db_con= mysql_connect($this->server, $this->username, $this->password);
if (!$db_con)
{
$this->con_error = mysql_error();
return false;
}
if(!mysql_select_db($this->database))
{
$this->con_error = mysql_error();
return false;
}
return $db_con;
die("Database connection failed: " . mysql_error());
$db_select = mysql_select_db("nameofdatabase",$connection);
mysql_select_db cannot possibly run here. It's only called after die.
$connection = mysql_connect("localhost","root");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("nameofdatabase",$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
Also it would be worth checking if you entered a password to your server.
$connection = mysql_connect("localhost","root"); (Missing Password)
The following code will trap any other error that might be happening and like the answer below this will provide mysql conectivity errors in case there is any.
try
{
$connection = mysql_connect("localhost","root", "password");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("nameofdatabase",$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
}catch (Exception $e){
error_log(" DB Error: ".$e->getMessage());
}
Related
I have create a database (student) and table(details) in SQL, Fields are Name,Class,Section,Address,Mobile. I need delete the Selva row in that table,I can't delete it please explain!!
PHP code-
<?php
$connection = mysql_connect('localhost', 'root','');
if (!$connection)
{
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db( "student",$connection);
if (!$select_db)
{
die("Database Selection Failed" . mysql_error());
}
?>
<?php
if(isset($_GET['did'])) {
$delete_id = mysql_real_escape_string($_GET['did']);
$sql = mysql_query("DELETE FROM details WHERE Name = 'Selva' ");
if($sql) {
header("Location: table1.php");
} else {
echo "ERROR";
}
}
?>
Please explain ! how to delete the row in a table from database.
Your mysql query is proper but you need to check below condition is satisfied or not.
if(isset($_GET['did'])) {
echo 'debug test';exit;
}
I'm trying to learn php and I can't read any data from my database!. I know the connection to the server is live and working but this line seem to be giving me problems.
$result = $conn->query($sql);
Where $sql = "SELECT firstName, middleName, lastName FROM Base";
I'm not sure what the problem is but any hints or answer are appreciated .
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My first PHP page</h1>
<?php
// connect to database
$user_name = "superUser";
$password = "";
$database = "Base"$server = "127.0.0.5";
// open connection to the server
$conn = new mysqli($server, $user_name, $password);
// echo "Connection to the server is open";
// check connetion
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
print "Connection to the server is open";
}
// load the data from the table
$sql = "SELECT firstName, middleName, lastName FROM Base";
// echo $conn->server_info;
$result = $conn->query($sql);
if ($result) {
echo "Table was found";
}
else echo "no";
/*while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br />";
}
print $result["firstName"];// ": Number of Rows!" ;*/
// if ($result->num_rows > 0) {
// output data of each row
// close server connection
$conn->close();
?>
</body>
</html>
The following is a mysqli connect 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();
}
?>
You forgot to add your database name.
Change this,
$conn = new mysqli($server, $user_name, $password);
to this
$conn = new mysqli($server, $user_name, $password, $database);
I'm having troubles getting my code to work properly. If I type it into phpMyAdmin it works, but when I try it in the code, it doesn't update the database.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
mysql_close($con);
?>
Try out this code snippet and see how you get on.
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con) {
die('Could not connect: ' . mysql_error());
} else {
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($query);
mysql_close($con);
}
?>
I would recommend doing it this way as mysql is no longer supported by PHP.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if (!$mysqli) {
die('Could not connect: ' . $mysqli->connect_error);
} else {
$sp = $mysqli->real_escape_string($_GET['file']);
$query = "UPDATE TDB SET WEIGHT=100000 WHERE PATH='$sp'";
$mysqli->query(query);
$mysqli->close();
}
?>
You're not EXECUTING your query. You're just defining a string that happens to contain some SQL, e.g.
$sql = "blah blah blah";
$result = mysql_query($sql) or die(mysql_error()); <--forgot this
<?php
$con = mysql_connect("SERVER","USER","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("DATABASE", $con);
$sp=mysql_real_escape_string($_GET['file']);
$sql = "UPDATE TRACKDB SET WEIGHT=100000 WHERE PATH='$sp'";
$result = mysql_query($sql) or die(mysql_error());
mysql_close($con);
?>
This seems like it should be so easy but I am not getting an error or any result:
$connection = mysql_connect("phpexamplesite.db.4211592.hostedresource.com", "username", "password");
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
//2. Select a database to use
$db_select = mysql_select_db("username", $connection);
if(!$db_select){
die("Database selection failed: " . mysql_error());
Any ideas?
THanks:)
sorry about that... I did put the query in:
// 3. Perform database query
$result = mysql_query("SELECT * FROM subjects", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use returned data
while($row = mysql_fetch_array($result)) {
echo $row["menu_name"]. " ".$row["position"]. "<br />";
}
?>
<?php
//5. Close connection
mysql_close($connection);
?>
I'm not getting any error or results on the page...
You probably just don't have any result from the select statement.
It could be from a syntax error. You are missing a closing brace in the first code snippet in
if(!$db_select)
{
die("Database selection failed: " . mysql_error()); `
**}**
Try running your file from the command line through php test.php
Some servers (Apache) are configured to not output anything if there is a syntax error.
I want to create a database. Why is not the db created with this code?
$dbname = 'regulations_db';
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_num_rows(mysql_query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '". $dbname ."'"))) {
echo "Database $dbname already exists.";
}
else {
mysql_query("CREATE DATABASE '". $dbname ."'",$con);
echo "Database $dbname created.";
}
This is working, but I think the first one is the best practice:
if (mysql_query("CREATE DATABASE IF NOT EXISTS regulations_db",$con))
{
echo "Database created";
}
else
{
echo "Error creating database: " . mysql_error();
}
Just do a simple mysql_select_db() and if the result is false then proceed with the creation.
As an example, check out the first answer here by another very smart StackOverflower.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Three steps to fix this:
Don’t specify the database name when connecting.
Your SQL statement should be CREATE DATABASE IF NOT EXISTS php1.
Call mysqli_select_db($link, 'php1') to make that the default database for your connection.
If you're using MySQLi Object-oriented method, you can use following code, this code is similar to previous answer and only the method is different, I just put this because if anyone using MySQLi Object-oriented method, you can use this code directly.
$servername = "localhost";
$username = "mysql_user";
$password = "user_password";
$dbName = "databaseName";
// Connect to MySQL
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// If database is not exist create one
if (!mysqli_select_db($conn,$dbName)){
$sql = "CREATE DATABASE ".$dbName;
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
}else {
echo "Error creating database: " . $conn->error;
}
}
Furthermore you can refer W3school site here.
Good Luck! :D