Trying to make code that will insert arabic data into mysql [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 5 years ago.
I have the following code which run when I press a button in an html form
<!DOCTYPE html>
<html>
<head>
<?php $timestamp = date("YmdHis"); ?>
<link rel="stylesheet" type="text/css" href="style.css"?v=<?php echo time(); ?>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Data Entry</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql->set_charset('utf8');
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS mortgagedb";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$sql = "CREATE TABLE IF NOT EXISTS mortgagedb . clientstest (
reg_date TIMESTAMP,
client_code INT(6) UNSIGNED PRIMARY KEY,
project_code INT(6) UNSIGNED NOT NULL,
client_name VARCHAR(255) NOT NULL,
client_id INT(14) NOT NULL,
client_id_expiry VARCHAR(7) NOT NULL,
client_address VARCHAR(255) NOT NULL,
client_profession VARCHAR(255) NOT NULL,
client_phone INT(12) NOT NULL,
income INT(6) NOT NULL,
guarantor_name VARCHAR(255) NOT NULL,
guarantor_id VARCHAR(14) NOT NULL,
guarantor_id_expiry VARCHAR(7) NOT NULL,
guarantor_address VARCHAR(255) NOT NULL,
guarantor_relation VARCHAR(255) NOT NULL,
unit_no VARCHAR(255) NOT NULL,
floor_no VARCHAR(255) NOT NULL,
bulding_no VARCHAR(255) NOT NULL,
location VARCHAR(255) NOT NULL,
project VARCHAR(255) NOT NULL,
city VARCHAR(255) NOT NULL,
governorate VARCHAR(255) NOT NULL,
area VARCHAR(255) NOT NULL,
unit_value INT(7) NOT NULL,
previous_payment INT(7) NOT NULL,
loan_maturity INT(2) NOT NULL,
mortgage_rate INT(2) NOT NULL,
annual_rate_wage INT(2) NOT NULL,
max_pay_inc INT(2) NOT NULL,
prog_max_inc INT(7) NOT NULL,
prog_min_inc INT(7) NOT NULL,
prog_max_sub INT(7) NOT NULL,
prog_min_sub INT(7) NOT NULL,
payment_graduation INT(2) NOT NULL,
iscore VARCHAR(255) NOT NULL,
documents VARCHAR(255) NOT NULL,
condition1 VARCHAR(255) NOT NULL,
condition2 VARCHAR(255) NOT NULL,
condition3 VARCHAR(255) NOT NULL,
condition4 VARCHAR(255) NOT NULL,
condition5 VARCHAR(255) NOT NULL,
condition6 VARCHAR(255) NOT NULL,
condition7 VARCHAR(255) NOT NULL,
condition8 VARCHAR(255) NOT NULL,
condition9 VARCHAR(255) NOT NULL,
condition10 VARCHAR(255) NOT NULL,
condition11 VARCHAR(255) NOT NULL,
condition12 VARCHAR(255) NOT NULL,
condition13 VARCHAR(255) NOT NULL,
condition14 VARCHAR(255) NOT NULL,
attachment1 VARCHAR(255) NOT NULL,
attachment2 VARCHAR(255) NOT NULL,
attachment3 VARCHAR(255) NOT NULL,
attachment4 VARCHAR(255) NOT NULL,
attachment5 VARCHAR(255) NOT NULL,
attachment6 VARCHAR(255) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table clientstest created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$sql = "INSERT INTO mortgagedb . clientstest (client_code, project_code, client_name, client_id, client_id_expiry, client_address, client_profession, client_phone, income, guarantor_name, guarantor_id, guarantor_id_expiry, guarantor_address, guarantor_relation, unit_no, floor_no, bulding_no, location, project, city, governorate, area, unit_value, previous_payment, loan_maturity, mortgage_rate, annual_rate_wage, max_pay_inc, prog_max_inc, prog_min_inc, prog_max_sub, prog_min_sub, payment_graduation, iscore, documents, condition1, condition2, condition3, condition4, condition5, condition6, condition7, condition8, condition9, condition10, condition11, condition12, condition13, condition14, attachment1, attachment2, attachment3, attachment4, attachment5, attachment6)
VALUES ('$_POST[ccode]', '$_POST[pcode]', '$_POST[cname]', '$_POST[cid]', '$_POST[ciddate]', '$_POST[caddress]', '$_POST[cjob]', '$_POST[cphone]', '$_POST[inc]', '$_POST[gname]', '$_POST[gid]', '$_POST[giddate]', '$_POST[gaddress]', '$_POST[grel]', '$_POST[un]', '$_POST[floor]', '$_POST[bn]', '$_POST[lctn]', '$_POST[pro]', '$_POST[city]', '$_POST[gov]', '$_POST[area]', '$_POST[unitv]', '$_POST[pp]', '$_POST[lm]', '$_POST[mr]', '$_POST[row]', '$_POST[paytoinc]', '$_POST[maxinc]', '$_POST[mininc]', '$_POST[maxsub]', '$_POST[minsub]', '$_POST[pgr]', '$_POST[iscore]', '$_POST[docs]', '$_POST[con1]', '$_POST[con2]', '$_POST[con3]', '$_POST[con4]', '$_POST[con5]', '$_POST[con6]', '$_POST[con7]', '$_POST[con8]', '$_POST[con9]', '$_POST[con10]', '$_POST[con11]', '$_POST[con12]', '$_POST[con13]', '$_POST[con14]', '$_POST[att1]', '$_POST[att2]', '$_POST[att3]', '$_POST[att4]', '$_POST[att5]', '$_POST[att6]' )";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
</html>
but I get the following error
Fatal error: Uncaught Error: Call to a member function set_charset()
on null in C:\xampp\htdocs\Mortgage Project\db.php:21 Stack trace: #0
{main} thrown in C:\xampp\htdocs\Mortgage Project\db.php on line 21
I know the error is about set_char, but I'm new and don't really understand the problem here , thanks in advance.

Your error comes from this line:
$sql->set_charset('utf8');
Basically its correct, but you haven't defined $sql at all. You need to use set_charset on your connection object.
So instead of your code, write:
$conn->set_charset('utf8');

You have $sql->set_charset('utf8');. However. $sql is only defined on the NEXT LINE!
Try changing it to $conn!

Related

PDO: Table not creating even after success message [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 4 years ago.
Here is the code snippet. I'm creating it for stock management in my shop:
$connect_stock = new PDO('mysql:host=localhost;dbname=daily_inventory', 'user', 'password');
$table_name = 'stock_'.date('dmY');
$query = "CREATE TABLE IF NOT EXISTS '$table_name' (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item` varchar(250) DEFAULT NULL,
`brand` varchar(250) DEFAULT NULL,
`gender` varchar(250) DEFAULT NULL,
`size` varchar(250) DEFAULT NULL,
`sleeve` varchar(250) DEFAULT NULL,
`fabric` varchar(250) DEFAULT NULL,
`style` varchar(250) DEFAULT NULL,
`wholesaler` varchar(250) DEFAULT NULL,
`extra_features` varchar(250) DEFAULT NULL,
`date_time` datetime DEFAULT CURRENT_TIMESTAMP,
`cost_price` decimal(10,2) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`product_code` varchar(250) DEFAULT NULL COMMENT 'product_code will be set to Not Null',
PRIMARY KEY (`id`)
)";
try {
$connect_stock->exec($query);
echo "Created $table_name Table.\n";
} catch(PDOException $e){
echo $e->getMessage();
}
This is always printing:
Created {table_name} Table.
But no tables are getting added in the database. What can be the problem here?
Remove single quotes (' ') from table name
Use $table_name instead of '$table_name' and try. This will work definitely

mysqli_query() expects parameter 1 to be mysqli, array given in

When I run the following query
$sql ="SELECT * FROM user_info JOIN Notifications ON user_info.user_info_id =Notifications.Sender_id AND Notifications.STATE=0 LIMIT 1";
$query=mysqli_query($con,$sql);
$num_rows=mysqli_num_rows($query);
$message=''
if($num_rows > 0){
$con=mysqli_fetch_assoc($query);
switch ($con['Notification_Type']){
case'events':
$var="Notifications".$con['user_info_id'];
$sql_shown="SELECT *FROMevent WHERE event.notification_shown = 0 AND event.user_info_id='$var'LIMIT 1";
$query_vi=mysqli_query($con,$sql_shown);
$num_rows_vi=mysqli_num_rows($query_vi);
$message.=$con['Sender_id']."has created a Event";
echo $message;
break;
}
}
I get the following error:
mysqli_query() expects parameter 1 to be mysqli, array given in
This is my user table:
CREATE TABLE IF NOT EXISTS user_info(
user_info_id INT(11) NOT NULL AUTO_INCREMENT,
u_first_name VARCHAR(255) NOT NULL,
u_last_name VARCHAR(255) NOT NULL,
u_email VARCHAR(255) NOT NULL,
u_mobile VARCHAR(255) NOT NULL,
role ENUM('1yearM','1yearN','1yearR','1yearU','1yearS','2M','2R','2N','2U','2S','3M','3R','3N','3U','3S','4M','4R','4N','4U','4S','professor','librarian','admission_department') NOT NULL,
password VARCHAR(255) NOT NULL,
u_ip VARCHAR(255) NOT NULL,
signup_date DATETIME NOT NULL,
last_login DATETIME NOT NULL,
act_code VARCHAR(255) NOT NULL,
activation enum('1','0') NOT NULL DEFAULT '0',
PRIMARY KEY (user_info_id),
UNIQUE KEY (u_email,u_mobile)
)
This is my event table:
CREATE TABLE IF NOT EXISTS Event(
Event_id INT(11) NOT NULL AUTO_INCREMENT,
Event_Name VARCHAR(255) NOT NULL,
Event_location VARCHAR(255) NOT NULL,
Event_Organizer VARCHAR(255) NOT NULL,
Event_Date_Posted DATETIME NOT NULL,
Event_Starting_timings DATETIME NOT NULL,
Event_Ending_timings DATETIME NOT NULL,
Event_Day VARCHAR(255) NOT NULL,
Event_Description text NOT NULL,
Event_file_name VARCHAR(255) NOT NULL,
Event_file_path VARCHAR(255) NOT NULL,
Event_file_size VARCHAR(255) NOT NULL,
user_info_id INT(11) NOT NULL,
notification_shown ENUM('1','0') NOT NULL DEFAULT '0',
PRIMARY KEY (Event_id),
FOREIGN KEY (user_info_id) REFERENCES user_info(user_info_id)
)
This is my notification table:
CREATE TABLE IF NOT EXISTS Notifications(
Notifications_id INT(11) NOT NULL AUTO_INCREMENT,
Notification_Type VARCHAR(255) NOT NULL,
Notification_Content VARCHAR(255) NOT NULL,
Notification_Created_Date DATETIME NOT NULL,
Notification_State ENUM('read','unread') NOT NULL DEFAULT 'unread',
Is_Notification_Delete ENUM('1','0') NOT NULL DEFAULT '0',
Notification_Deleted_Date DATETIME NOT NULL,
Sender_id INT(11) NOT NULL,
STATE ENUM('1','0') NOT NULL DEFAULT '0',
Recipient_id INT(11) NOT NULL,
PRIMARY KEY (Notifications_id)
)
You overwrite your $con variable with this line:
$con=mysqli_fetch_assoc($query);
Before that line your $con variable was a valid MySQLi connection handle. After that line it is not an array. Therefore your mysqli_query() call complain that the first argument isn't a mysqli connection/object/handle anymore, but instead is now an array (which it shouldn't).
Change your $con=mysqli_fetch_assoc($query); so it doesn't overwrite your $con variable with the MySQLi connection/object/handle, but instead write the result in a different variable (maybe $userinfo?).
Check if your $con it's been created with properly method mysqli_connect('').

PHP Fatal error: Call to undefined function pdo_query()

No answers were found at google and stackoverflow
The code is as follows
<?php
pdo_query("CREATE TABLE IF NOT EXISTS `ims_cyl_vip_video` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uniacid` int(5) NOT NULL,
`title` varchar(255) NOT NULL,
`uid` varchar(25) NOT NULL,
`openid` varchar(255) NOT NULL,
`time` varchar(15) NOT NULL,
`video_url` text NOT NULL,
`share` int(3) NOT NULL,
`yvideo_url` text NOT NULL,
`type` VARCHAR(25) NOT NULL,
`index` int(2) NOT NULL,
`video_id` int(11) NOT NULL,
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `ims_cyl_vip_video_member` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`uniacid` int(10) NOT NULL,
`openid` varchar(255) NOT NULL,
`uid` varchar(25) NOT NULL,
`nickname` varchar(255) NOT NULL,
`avatar` varchar(1000) NOT NULL,
`end_time` varchar(15) NOT NULL,
`is_pay` int(2) NOT NULL,
I think you are trying to create a table with PHP. Here is the simple code example from which you can create the tables: Replace the sample query with your SQL query.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_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 ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>

Not Creating Table with PDO

I have a sql command that I am trying to execute using PDO and it executes true, but the table is not created. I have no idea what I am doing wrong. I looked around the internet to see if anyone else has had this problem, but I didnt really seem to find anything that fixes it. Here is the SQL Command
CREATE TABLE table_230
(
id VARCHAR(255),
cost VARCHAR(255),
title VARCHAR(255) NOT NULL,
package_quantity VARCHAR(255) NOT NULL,
package_cost VARCHAR(255) NOT NULL,
asin VARCHAR(15) NOT NULL,
rank VARCHAR(20) NOT NULL,
category VARCHAR(255) NOT NULL,
bb_price VARCHAR(255) NOT NULL,
seller_type VARCHAR(255) NOT NULL,
size_tier VARCHAR(255) NOT NULL,
amazon_fee VARCHAR(255) NOT NULL,
roi VARCHAR(255) NOT NULL,
parent_asin VARCHAR(255) NOT NULL,
complete TINYINT(1) DEFAULT 0
)
The command runs in PHPMyAdmin when I attempt to execute it, but it does not work when I use PDO. The code that I use looks like this:
$create = $this->dbConnection->prepare("
CREATE TABLE IF NOT EXISTS table_" . $tableId ."
(
id VARCHAR(255),
cost VARCHAR(255),
title VARCHAR(255) NOT NULL,
package_quantity VARCHAR(255) NOT NULL,
package_cost VARCHAR(255) NOT NULL,
asin VARCHAR(15) NOT NULL,
rank VARCHAR(20) NOT NULL,
category VARCHAR(255) NOT NULL,
bb_price VARCHAR(255) NOT NULL,
seller_type VARCHAR(255) NOT NULL,
size_tier VARCHAR(255) NOT NULL,
amazon_fee VARCHAR(255) NOT NULL,
roi VARCHAR(255) NOT NULL,
parent_asin VARCHAR(255) NOT NULL,
complete TINYINT(1) DEFAULT 0
)");
if($create->execute() === true)
{
return true;
}
It always returns true. If someone could help me out, I would really appreciate it!
Set up your connection first:
$mysql_host = "servername";
$mysql_database = "dbname";
$mysql_user = "username";
$mysql_password = "pass";
try{
$conn = new PDO(
"mysql:dbname=" . $mysql_database .
";host=" . $mysql_host .
";charset=utf8" ,
$mysql_user ,
$mysql_password ,
array( //
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
)
);
}catch(PDOException $e){
echo $e->getCode();
}
Then query:
$tableId=$conn->lastInsertId();
$create = $conn->prepare("
CREATE TABLE IF NOT EXISTS table_" . $tableId ."
(
id VARCHAR(255),
cost VARCHAR(255),
title VARCHAR(255) NOT NULL,
package_quantity VARCHAR(255) NOT NULL,
package_cost VARCHAR(255) NOT NULL,
asin VARCHAR(15) NOT NULL,
rank VARCHAR(20) NOT NULL,
category VARCHAR(255) NOT NULL,
bb_price VARCHAR(255) NOT NULL,
seller_type VARCHAR(255) NOT NULL,
size_tier VARCHAR(255) NOT NULL,
amazon_fee VARCHAR(255) NOT NULL,
roi VARCHAR(255) NOT NULL,
parent_asin VARCHAR(255) NOT NULL,
complete TINYINT(1) DEFAULT 0
)");
if($create->execute() === true)
{
return true;
}
This code works. Are you sure your $tableId variable is having expected value? you should var_dump($tableId) to see what's in it!

Create tables in database from queries in a text file

I have the following PHP page to create a table using a text file.
table_create.php
<?php
include $db;
$query_file = "sql.txt";
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
$retval = mysql_query($sql);
if(! $retval )
{
die("Could not create the tables<br>");
}
echo "Table created successfully<br>";
?>
sql.txt
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
CREATE TABLE ht_bank (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(50) NOT NULL,
ac_no varchar(50) NOT NULL,
address varchar(50) NOT NULL);
CREATE TABLE ht_user_role (
id int(11) NOT NULL AUTO_INCREMENT,
value varchar(50) NOT NULL);
When I try to create a single table in the sql.txt file, the code works perfectly.
For example:
CREATE TABLE ht_account (
id int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
type varchar(50) NOT NULL,
mode varchar(50) NOT NULL,
party varchar(50) NOT NULL,
payee varchar(50) NOT NULL,
rate decimal(13,2) NOT NULL,
box int(11) NOT NULL,
amount decimal(13,2) NOT NULL,
token varchar(50) NOT NULL,
remarks varchar(50) NOT NULL,
user varchar(50) NOT NULL,
user_confirm varchar(50) NOT NULL,
status varchar(50) NOT NULL);
But when I try to create multiple tables, It does not create any table. I doubt that the format in the sql.txt may be incorrect.
The format is, almost sure, correct but mysql_query doesn't work with multiple queries:
mysql_query() sends a unique query (multiple queries are not
supported) to the currently active database on the server that's
associated with the specified link_identifier.
It's better to use mysqli functions because mysql ones are deprecated for PHP 5.5 and mysqli has the function mysqli_multi_query that you need.
If you still want to use mysql functions you could do something like:
$sql_array=explode(';',$sql);
foreach ($sql_array as $s) {
if(! mysql_query($s)){
echo mysql_error()."<br>";
}
}

Categories