I'm inserting utf-8 data to the database with this code
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "INSERT INTO Movies (Name, Year)
VALUES ('".$_POST["name"]."', '".$_POST["year"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
But the data is added like this:
What should I do?
This is something I think you must fix in the back end, the PHP code is perfect, but you need to configure your database to utf-8 as well. You appear to be using PHPmyAdmin, when you create or import the table, you should see a drop down box to select the file's character set. Change this and you should be good to go!
That should start (end?) with Arabic 'noon' (ن), correct?
ن is the "html entity" for 'noon'.
Was the user filling in an html <form>? does it include a charset, such as <form accept-charset="UTF-8">? If not, that might be the solution.
Is the column/table declared CHARACTER SET utf8 (or utf8mb4, but not utf32)? It needs to be. See SHOW CREATE TABLE.
You can use alter command in mysql to change all the fields to utf8 format,
Please check the sql query
ALTER TABLE `Movies` CHANGE `Name` `Name` VARCHAR(40) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL;
Related
I have a insert query from PHP file to database.
While executing the query from MySQL Workbench it is inserting last_used value in database exact time given in the query. But when I try to run the same query from PHP code it is inserting 1 day future date.
In both scenarios created_at inserting correct value which is mentioned in the table structure
I have set timezone to Asia/Kolkata in php.ini file.
I have searched a lot in the google and executed all the things mentioned by all.
<?php
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `login_token` (`userid`, `username`, `token`, `last_used`, `role_id`) VALUES ('aiIRX+5v35p4vOokrgVR+Q==', '/McgiDGM0JpsyCSie2cIV4sTwrtkE+ev', 'token1', '2022-09-19 12:47:59', '')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
Table Structure
Result of records inserted from php
As you see in the above question i have last_used column in database with TIMESTAMP datatype. I have a insert query in my php code. If i run the query in php it is inserting '2022-09-20 01:77:59' instead of '2022-09-19 12:47:59'. If i run the same query in mysql workbench it is inserting same value '2022-09-19 12:47:59''
when i echo date('Y-M-d H:i:s') it is showing correct time which is matched with my local machine.
when i run SELECT CURRENT_TIMESTAMP() in workbench it is also showing same time which is given in date() in php.
Add bellow line in php.ini file
date.timezone = Asia/Kolkata
Add bellow line in my.ini file
default-time-zone = "Asia/Kolkata"
Important Note : stop and start both Apache and MySQL in XAMPP control panel to apply changes.
Better to add date_default_timezone_set('Asia/Kolkata'); in first line of your PHP file after php tag starts
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);
?>
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.
This question already has answers here:
The ultimate emoji encoding scheme
(2 answers)
Closed 6 years ago.
I am having problems decoding UTF8 characters in my script from my sql.
Lets say I have two characters coming from mysql:
'á' & ❤️
with my script á is decoded fine however, the emoticon is decoded in â¤ï
What am I doing wrong?
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM `community` ORDER BY `community`.`date` DESC LIMIT 25";
mysqli_set_charset($conn, "utf8"); //UTF8
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$comment = $row['comment'];
echo $comment . "</br>";
//echo htmlentities($comment); not working... white screen
}
UPDATE
I have changed Database and Tables
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT * FROM `community` ORDER BY `community`.`date` DESC LIMIT 25";
mysqli_set_charset($conn, "utf8"); //UTF8
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$comment = $row['comment'];
$comment = mb_convert_encoding($comment, "UTF-8");
echo $comment . "</br>";
//echo htmlentities($comment); not working... white screen
}
Your issue here is probably with the database.
You need to set your database charset to UTF-8 in order to query it correctly, what you are doing is to get a string and setting Client side default charset using
mysqli_set_charset($conn, "utf8"); //UTF8
That's not enough, so I would recommend you to run an SQL query like
ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
in order to update it. If what you need is to change a single table use
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Finally you can check it using
SELECT DEFAULT_COLLATION_NAME FROM data_dictionary.SCHEMAS WHERE SCHEMA_NAME = 'databasename' LIMIT 1;
As an extra appointment and just in case in PHP you can convert the encoding of a string using
$comment = mb_convert_encoding($comment, "UTF-8"); //Change encoding
echo mb_detect_encoding($str, "auto"); // Check encoding
Of course you should make a backup before making any of these changes, just in case.
EDIT: The proper order to run these queries, is:
Run it in the whole DB using the first query
Run it table by table using the second query
Check if the charset has been set correctly using the third query
EDIT 2 : Remember to set the tag <meta charset="UTF-8"> in your html file.
I hope this helps you :)
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.