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.
Related
Struggling now for a day. Need to make a database in PHP (if not existing) and after make sure it is empty (if already was existing). But somehow I probably miss something essential and nothing happens. Looks like it just skips the creation and the delete part altogether.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//Database variables
$servername = "localhost";
$username = "Somename";
$password = "Verysecret";
$dbname = "TESTDB";
$temptable = "tablename";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: ",$dbname,"<br>" ;
?><br><?php
//Create table if not existing yet (syntax error here?)
echo "Creating table if non existing","<br>";
$conn->select_db('$dbname');
$sql = "CREATE TABLE IF NON EXIST `{$temptable}` (
`xml_date` datetime,
`xml_duration` int(2),
`xml_boat` VARCHAR(30),
`xml_itinerary` VARCHAR(30),
`xml_dep_arr` VARCHAR(30),
`xml_spaces` INT(2),
`xml_rate_eur` decimal(4,2),
`xml_rate_gbp` decimal(4,2),
`xml_rate_usd` decimal(4,2))";
//This part not showing up in output at all!
if(mysqli_query($conn, $sql)){
echo "Table created successfully";
} else {
echo "Table is not created successfully ";
}
//Deleting rows if table existed already (same syntax error here?)
echo "Making sure table is empty","<br>";
$sql = "DELETE * FROM `{$temptable}`";
mysqli_close($conn);
?>
All I see when I run (Localy with Mamp)is:
Connected successfully to
database: TESTDB
Creating table if non existing Making sure table is empty
The Database is not created, when I create it myself in SequelPro before and add some rows.
Help, searching now a day! What am I doing wrong? Lost in quotes, back quotes, double quotes? Overseeing the obvious?
Let's iterate over what you used here.
DELETE *, is invalid since the asterisk is used for SELECT and not DELETE.
The basic syntax is DELETE FROM TABLE WHERE col_x = ? (with optional WHERE clause).
Example:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
https://dev.mysql.com/doc/refman/5.7/en/delete.html
Your table creation syntax is incorrect, the basic syntax is:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
as per the documentation.
https://dev.mysql.com/doc/refman/5.7/en/create-table.html
which uses the keywords IF NOT EXISTS and not your IF NON EXIST.
You also didn't execute the DELETE query.
http://php.net/manual/en/mysqli.query.php
and check for errors on it also:
http://php.net/mysqli_error
Plus, as Chris was so nice to point out in comments; variables don't get parsed in single quotes.
Either remove them from $conn->select_db('$dbname'); as in either
$conn->select_db($dbname);
or set in double quotes:
$conn->select_db("$dbname");
Edit:
If the goal here is to get rid of the table entirely (after and seeing your DELETE query), then both DELETE and TRUNCATE are not what you want to use here, but DROP TABLE.
Consult the documentation:
https://dev.mysql.com/doc/refman/5.7/en/drop-table.html
Basic example:
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
Try this , i got the table created
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//Database variables
$servername = "localhost";
$username = "detecttn_user";
$password = "Azer12345";
$dbname = "detecttn_teststack";
$temptable = "test ";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: $dbname <br>" ;
?><br><?php
//Create table if not existing yet (syntax error here?)
echo "Creating table if non existing","<br>";
$sql ="SHOW TABLES LIKE '$temptable'";
if(mysqli_query($conn, $sql)){
echo "Table exist";
} else {
echo "Table does not exist";
// if table not exist create it
$sql = "CREATE TABLE IF NOT EXISTS $temptable (
`xml_date` datetime,
`xml_duration` int(2),
`xml_boat` VARCHAR(30),
`xml_itinerary` VARCHAR(30),
`xml_dep_arr` VARCHAR(30),
`xml_spaces` INT(2),
`xml_rate_eur` decimal(4,2),
`xml_rate_gbp` decimal(4,2),
`xml_rate_usd` decimal(4,2))";
mysqli_query($conn, $sql);
$sql ="SHOW TABLES LIKE '$temptable'";
if(mysqli_query($conn, $sql)){
echo "Table created";
} else {
echo "Table creation failed";
}
}
//Deleting rows if table existed already (same syntax error here?)
echo "Making sure table is empty","<br>";
$sql2 = "TRUNCATE TABLE $temptable";
if(mysqli_query($conn, $sql2)){
echo "Table is empty";
} else {
echo "Error";
}
mysqli_close($conn);
?>
We have a phone system database on one server that we cloned/dumped to our local server, but now we need to keep our version updated. Obviously, tables and schema are the same, I just want to run this scheduled script to update with new records that don't exist on the local table (i.e. records that were created since last update).
Below is a test select/insert block. The select query worked on it's own originally, but now I've modified it to use a loop with hopes of using numrows and a foreach to capture everything in the select.
The session table has about 35 columns so I'm looking for the best way to go about this without having to declare every column. I originally tried to do this using update on duplicate key or insert/ignore using a not exists but I don't really know what I'm doing.
Basically, once I select everything, if my table on server 2 doesn't contain a record with the SESSIONID primary key, I want to insert it. I just need some assistance creating this loop script.
Example:
if the table on server 1 has 2 rows with sessionID 12345, and 12346, but my table on server 2 only has up to sessionID 12344, I want to insert the whole records for those two IDs.
//Defining credentials
$servername = "";
$username = "";
$password = "";
$servername2 = "";
$username2 = "";
$password2 = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Query to select * from Session table on server 1
$query1 = "select * from cdrdb.session";
$results = mysqli_query($conn1, $query1);
foreach ($results as $r => $result) {
$stmt1 = mysqli_prepare($conn2, "insert into ambition.session a where not
exists(a.SESSIONID)");
mysqli_stmt_execute($stmt1) or die(mysqli_error($conn2));
}
This is not duplicated question, since I am asking how to use SET and INSERT in one PHP variable, there no any questions about AUTO_INCREMENT...
I have below page:
<?php
function genWO(){
$dbtype = "MySQL";
$username = "user";
$password = "pass";
$hostname = "10.10.10.10";
$dbname = "TABLES";
//connection to the database
$conn = new mysqli($hostname, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
if ($conn->query($insertNewWONum) === TRUE) {
echo "New record created successfully". "<br>";
} else {
echo "Error: " . $insertNewWONum . "<br>" . $conn->error;
}
$getWONum = "SELECT LPAD(max(WO_NUM) ,6,0) as NEW_WO_NUM from GENERIC_TABLES.WO_NUMBERS";
$result = $conn->query($getWONum);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "New WO Number: " . $row["NEW_WO_NUM"]. "<br>";
}
} else {
echo "0 results";
}
//close the connection
$conn->close();
}
?>
Since it is not allowed to use INSERT and SELECT for the same table in one query, I am trying to set variable and use it in INSERT query:
$insertNewWONum = "SET #MAX_WO = (SELECT max(WO_NUM) + 1 from GENERIC_TABLES.WO_NUMBERS); INSERT INTO GENERIC_TABLES.WO_NUMBERS (WO_NUM, WO_REQUESTOR) values (#MAX_WO, `test`)";
But it doesnt work, though it works fine if I am using this query in terminal.
Can anyone let me know how to achieve it please?
Since it is not allowed to use INSERT and SELECT for the same table in one query
All issues with your approach aside of course you can use INSERT and SELECT in one statement
INSERT INTO WO_NUMBERS (WO_NUM, WO_REQUESTOR)
SELECT COALESCE(MAX(WO_NUM), 0) + 1, 'Test'
FROM WO_NUMBERS;
Here is SQLFiddle demo.
Now what you need to realize is that your approach is unsafe for concurrent access. If this code is executed from two or more sessions simultaneously some or all of them may generate the same number effectively breaking your application.
Use AUTO_INCREMENT instead.
CREATE TABLE WO_NUMBERS
(
WO_NUM INT PRIMARY KEY AUTO_INCREMENT,
WO_REQUESTOR VARCHAR(32)
);
INSERT INTO WO_NUMBERS (WO_REQUESTOR) VALUES ('Test');
Here is SQLFiddle demo.
If for some reason you can't use AUTO_INCREMENT directly (and I honestly don't see why you couldn't) i.e. you need to add prefixes or augment the generated id/code in some way you can look this answer.
I want to make my PHP check if something with the same specific data already exists in my database table.
I have a database called test with a table called users.
This is where I would like to check if a row steamid already exists with the same $steamid number.
<?php
// Datebase infomation
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$steamid = $steamprofile['steamid'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create data
$sql = "INSERT INTO users (steamid)
VALUES ('$steamid')";
if (!$conn->query($sql) === TRUE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
you need to add a PRIMARY KEY or a UNIQUE constraint on the steamid column.
after deleting all the duplicates, then you can run this command:
ALTER TABLE users ADD PRIMARY KEY(steamid)
then your query will fail if you attempt to insert a duplicate steamid into the users table.
as #Jeremy mentioned, you can use REPLACE, but this also only works if you have a PRIMARY KEY or UNIQUE constraint on the column. this is the preferred method if you have additional columns aside from the steamid that you want to store in the database table because it will update those values. however, since your query as stated in the question INSERT INTO users (steamid) VALUES ('$steamid') only contains the one field, then it's not of much consequence unless you want to catch the conditional error of an attempted duplicate record, in which case you should stick to the INSERT statement.
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.