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.
Related
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.
I have just created a MySQL database named "test2" using PDO. Now I'm trying to create a table named "Visiteurs" but it seems my code do not work properly.
The error echoed is:
"SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected"
(which is wrong I think) and my code is the following:
$serveur = "localhost";
$login = "root";
$pass = "root";
try{
$conn = new PDO("mysql:host = $serveur; dbname = test2", $login, $pass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$codesql = "CREATE TABLE Visiteurs (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
nom VARCHAR(50) NOT NULL,
prenom VARCHAR(50) NOT NULL,
email VARCHAR(70)
)";
$conn->exec($codesql);
echo 'Table "Visiteurs" créée !';
}
catch(PDOException $e) {
echo 'Echec : ' . $e->getMessage();
}
Can someone help me find where is the error?
Althout the PDO MySQL DSN string documentation is not specific about whitespace, experience tells me that whitespace is not permitted in a DSN string. Since you have dbname = test2, the dbname is not actually being parsed and used, so PDO complains that no database was selected. Your DSN should look like the following, with no spaces between the key=value pairs:
"mysql:host=$serveur;dbname=test2"
You mentioned in comments that a previous connection succeeded and you were able to issue a CREATE DATABASE statement. That was only due to the coincidence of the default host being localhost and your $serveur variable being set to localhost as well. PDO probably did not parse the host= parameter from the DSN, but instead used localhost as the default connection with your user credentials. Since a CREATE DATABASE statement does not need to have a database selected, the dbname= was irrelevant.
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
I am a beginner in MySQL and I'm trying to enter some values in my database. The database is already made and its based localy.
I have a Schema named 'test' and within the schema I have a table named 'contacts'. Within the contacts I have an id, first and last name.
So I am trying to enter some data in the contacts. This is my php file:
<?
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
When I run the file on my browser, my database doesnt get any values. How can I execute that file so that John Smith gets added to my database?
Your php file has to start with <?php instead of <?.
Try this:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
Change
mysql_query($query);
to
mysql_query($query) or trigger_error(mysql_error() . $query);
then all will be revealed.
You might consider trying PHP ADODB and using AutoExecute with INSERT, if you know your field names
$db->AutoExecute('tablename',array('field1'=>'value','field2'=>'value'));
Can also be used for update:)
http://adodb.sourceforge.net/
First how is the structure of your table? If you have only 2 fields on the table that is the error if not please try to post the error the console gives back to you.
$query = "INSERT INTO contacts (first,last) VALUES ('John', 'Smith')";
$e=mysql_fetch_assoc($query);
also do not forget that your table structure says not null for the field id and the default value is null, so it will not accept this kind of insertion
Your ID is probably auto_increment, if so add order of attributes to your query :
INSERT INTO contacts(`first_name`, `last_name`) VALUES ('John','Smith')
Replace first_name and last_name with your real column names.
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.