Failed to find database? - php

So it seems that when I run the file register.php (which contains some basic html forms to send to a database) it cannot find the specific database that it is looking for. All files are with in the same folder, and the spelling is correct.
So I will paste the php code that is above all the html/css code in my register.php
<?php
$link=mysql_connect("localhost","root","");
$database='salesinformation';
if (!$link)
die('Failed to connect to Server'.mysql_error());
$db=mysql_select_db($database, $link);
session_start();
if(!$db)
die('Failed to select Data Base '.mysql_error());
if(isset($_GET['process']))
{
$query = "Insert INTO `sales` (Username, Email, Price, Condition, RegisterDate) values('$_POST[Username]', '$_POST[Email]','$_POST[Price]','$_POST[Condition]','$_POST[RegisteredDate]')";
//echo $query; exit;
$result = mysql_query($query) or die(mysql_error());
if(!$result){
$msg = "not Inserted";
}
else
{
$msg = "Inserted";
header("location:ClientList.php?m=".$msg);
}
}
?>
And I have the database file salesinformation.sql in the same folder which contains this code..
CREATE TABLE IF NOT EXISTS `sales` (
`Username` varchar(25) NOT NULL,
`Email` varchar(25) NOT NULL,
`Price` int(10) NOT NULL,
`Condition` varchar(25) NOT NULL,
`RegisterDate` date NOT NULL,
PRIMARY KEY (`Username`)
);
So this happens when I run xampp "http://localhost/register.php"
Failed to select Data Base Unknown database 'salesinformation'

And I have the database file salesinformation.sql in the same folder which contains this code..
That does not mean you have a MySQL database.
1) Create a MySQL database named salesinformation.
2) Import your SQL file into that database.
3) Now you have one. Now run your code.
Could you write what to type in the terminal (Since I cant find any GUI of the xampp while running it in ubuntu)? How do I create the "MySQL" database? and how to I import a SQL file into it?
Using terminal, type CREATE DATABASE salesinformation;
Using shell cd go to the directory where your salesinformation.sql file resides.
Issue this command mysql -u root -p password salesinformation < salesinformation.sql.
Note: Since I noticed from your code your root password is blank, you can remove the password term from the above command. If you do have a password type it there then

Related

MySQLi cannot create new table in PHP

I'm getting frustrated with running basic SQL statements in PHP. I keep running into syntax errors that ask me to refer to the current server version of MySQL.
I'm trying to run the follow SQL query:
CREATE DATABASE mc_todo_app;
use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
task VARCHAR(255) NOT NULL,
completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
In PHP I then try to run this script.
require "config.php";
// Create connection
$conn = mysqli_connect($host, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = file_get_contents('data/init.sql');
$result = mysqli_query($conn, $sql);
if (false === $result) {
printf("Error: %s\n", mysqli_error($conn));
} else {
echo "DB and Table successfully created!";
}
mysqli_close($conn);
This produces the following error message:
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 'use mc_todo_app;
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT,
tas' at line 3
Here are the details of my Database server:
I'm even trying basic Table creation statements from W3Schools without success.
What am I doing wrong?
mysqli_query() can only execute one query at a time, while you are attempting to execute multiple queries. You can use mysqli_multi_query() instead.
$sql = file_get_contents('data/init.sql');
$result = mysqli_multi_query($conn, $sql);
http://php.net/mysqli.multi-query

How to add a new column in MySQL using PHP?

How to add a new column in MySQL using PHP? I tried to do it many hours, but I can not solve my issue. Code:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxxxxx";
$DB_PASSWORD = "xxxxxx";
$DB_NAME = "xxxxxx";
$connect = mysql_connect($DB_HOST,$DB_USER,$DB_PASSWORD);
$db="test_table";
if (! $connect)
die(mysql_error());
mysql_select_db($db , $connect) or die("Select Error: ".mysql_error());
$result=mysql_query("ALTER TABLE id
ADD street VARCHAR(30) AFTER birthday,
Add city VARCHAR(30) AFTER street,
ADD state VARCHAR(4) AFTER city,
ADD zipcode VARCHAR(20) AFTER state,
ADD phone VARCHAR(20) AFTER zipcode") or die("Alter Error: ".mysql_error());
mysql_close($connect);
print "Field added";
?>
When I test this code an error appears:
Select Error: Access denied for user 'xxxxxxxxxxxx'#'localhost' to database 'test_table'
How can I do that?
First be sure your user has the right privileges as described in this so question here
Probably need to run some mysql like this:
GRANT ALTER ON example_table TO 'someuser'#'somehost';
Then similar code to the following should work.
<?php
$db = new mysqli('localhost','USERNAME','PASSWORD','DATABASENAME');
$sql = '
ALTER TABLE id
ADD street VARCHAR(30) AFTER birthday,
Add city VARCHAR(30) AFTER street,
ADD state VARCHAR(4) AFTER city,
ADD zipcode VARCHAR(20) AFTER state,
ADD phone VARCHAR(20) AFTER zipcode';
try {
$r = $db->prepare($sql);
$r->execute();
}
catch(Exception $e) {
error_log(print_r($e->getMessage(),1).' '.__FILE__.' '.__LINE__, 0);
}
Your MySQL user do not have access to your database, but you can connect to your MySQL server (it gives back an error message) and login there.
This means, that the user is not privileged to use your database test_table, please check again the database name (in your example, you give a table name, make sure you are using the database name and not a table name!). Also, you can try it with root account, if it is your server.
This is not a problem of your code but of authentification. Make sure you use the correct information.

INSERT & CREATE TABLE doesn't seem to be working

I'm currently experiencing some problems.
Basically, I use PDO and I want to create a table and insert some stuff into the table.
I've tried searching for solutions, but it doesn't seem like anything is working.
Please take a look at this:
public function install()
{
global $con;
$sql = "CREATE TABLE if not exists users
(id INT(11) PRIMARY_KEY,
uname VARCHAR(30) ,
pass VARCHAR (40))";
$sq = $con->query($sql);
if ($sq)
{
echo "Table successfully created!";
}
else
{
$this->errors[] = 'Error creating table: users';
}
$sql_code = "INSERT INTO users (
`uname`,
`pass` ) VALUES(
`$this->username`,
`$this->password`
)";
$sq1 = $con->query($sql_code);
if ($sql_code)
{
echo "Successfull!";
}
else
{
echo "Error creating admin user!";
}
}
NOTE: The database connection is set in another file called config.php and I've also included the config.php file to the code.
Well, there could be plenty of things going on, perhaps at the same time.
Maybe your database connection is failing (I'd recommend passing the connection $con by reference to the function install rather than using the global keyword).
Maybe you don't have enough rights to create a table in the database.
Also you are not binding your parameters, this would be the correct way to do it:
$sql_code = "
INSERT INTO users (
uname,
pass
)
VALUES (
:userName,
:password
);
";
$sq1 = $con->prepare($sql_code);
$sq1->bindParam(':userName', $userName);
$sq1->bindParam(':password', $password);
$sq1->query($sql_code);

Roleback CREATE TABLE using MySql Transactions

I'm writing a upgrader for a mysql database using PHP. The behavior of the upgrader should be as follows.
If all the queries executed successfully the changes should be committed.
If a sinngle query get faild eveything should be roled back to previouse state.
Part of my program is as follows.
$host = 'localhost';
$user = 'root';
$password = 'root';
$db = 'transaction';
$con = mysqli_connect($host, $user, $password);
mysqli_select_db($con, $db);
mysqli_autocommit($con, FALSE);
$query1 = "create table `status` (
`id` int not null auto_increment,
`name` varchar(60) not null,
primary key (`id`)
) engine=innodb default charset=utf8;";
$result1 = mysqli_query($con, $query1);
$query2 = "ALTER TABLE status
CHANGE name value varchar(512);";
$result2 = mysqli_query($con, $query2);
if(!($result1 && $result2)) {
mysqli_rollback($con);
} else {
mysqli_commit($con);
}
mysqli_close($con);
But if the 'status' table already exists the first create table query is failing. So both queries should be rolled back. But the alter query has executed and not rolled back.
I saw a post which list all the queries which cannot be rolled back in mysql. http://www.sitepoint.com/mysql-transaction-gotchas-good-parts/
Is there any possible way to do this role back in mysql.
No. You would need to run a new alter table query undoing your previous alter statement.
do it manualy
if(!($result1 && $result2)) {
#drop table
$query1 = "drop table `status`";
$result = mysqli_query($con, $query1);
}
Would it be better to just export the data into (say) a collection of CSV files. Then modify any dataif needed to match the new structure. Then just create the database with the new structure and import the data into it.
Seems a simpler solution that trying to make an upgrader.

PHP + MySQL is complicated

I am using XMAPP and MySQL is running as it should. In phpMyAdmin, I don't really get the point so I tried creating one in PHP. With this code it tells me the database benutzer. benutzer doesn't exists although I created one in phpMyAdmin and in this code:
<?php
$connect = mysql_connect("127.0.0.1","root","") or die ("Alles scheisse!");
$db = mysql_select_db("benutzer") or die ("Keine benutzer!");
$sql = "CREATE TABLE 'benutzer'
id VARCHAR(100),
name VARCHAR(100),
mail VARCHAR(100),
points INT(1000)
)";
$sql = "INSERT INTO benutzer(`id` , `name` , `mail` , `points`)VALUES(NULL , 'Liam', 'liam#mail.com', '100');";
$db_erg = mysql_query($sql)
or die("Anfrage fehlgeschlagen: " . mysql_error());
?>
Have you also created a table "benutzer" inside db "benutzer"? Your code does not execute your first SQL statement "CREATE TABLE.." so there will be no table "benutzer" if you don't have one created in phpmyadmin.
Did you created the database under the root user? Because you are connecting to the root in your code.

Categories