Not Creating Table with PDO - php

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!

Related

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('').

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

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!

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>";
}
}

Pagination using category ID

I am facing an issue with pagination which display details using an category ID.
Below is the database table which we are using to fetch the data. We are getting some errors and data was not printing in the page. I have added the page code in Pastebin. Where is the error I have done?
PHP page code: http://pastebin.com/EXmu5X67
Database table: http://pastebin.com/ZiBhPDTd
--
-- Table structure for table `plot_details`
--
CREATE TABLE IF NOT EXISTS `plot_details` (
`plot_detailsid` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` text NOT NULL,
`imgname` varchar(100) NOT NULL,
`imgname1` varchar(100) NOT NULL,
`imgname2` varchar(100) NOT NULL,
`imgname3` varchar(100) NOT NULL,
`imgname4` varchar(100) NOT NULL,
`cid` varchar(100) NOT NULL,
`city` varchar(100) NOT NULL,
`locality` varchar(700) NOT NULL,
`sqft` varchar(100) NOT NULL,
`acre` varchar(100) NOT NULL,
`cent` varchar(100) NOT NULL,
`sqm` varchar(100) NOT NULL,
`bedroom` varchar(100) NOT NULL,
`bathroom` varchar(100) NOT NULL,
`price` varchar(100) NOT NULL,
`owner_type` varchar(100) NOT NULL,
`video_title` varchar(100) NOT NULL,
`url` varchar(100) NOT NULL,
`covered_area` varchar(400) NOT NULL,
`feet` varchar(400) NOT NULL,
`random_id` varchar(200) NOT NULL,
`email` varchar(200) NOT NULL,
`pnumber` varchar(100) NOT NULL,
`status` int(11) NOT NULL,
`field` varchar(100) NOT NULL,
`url_page` varchar(200) NOT NULL,
PRIMARY KEY (`plot_detailsid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=242 ;
I found the answer for my question below is the answer
block:
session_start();
we need to add a session start for this to get the value to be store. so the pagination will use the session id and work on all pages

Multiple prepared statements with MYSQLI

I just moved to mysqli and I was wondering: can I do a multiple query with the prepared statements?
Here is the example: I need to check if this username is also in the table "future_user" and not just in "user" as it is doing right now. For code appeal I'd rather not write again the same function just changing "user" with "future_user".
function isFreeUsername($string)
{
$DB = databaseConnect();
$stmt = $DB->prepare("SELECT * FROM user WHERE username=? LIMIT 1");
$stmt->bind_param("s", $username);
if(isset($_SESSION) && isset($_GET['username'])) $username = $_GET['username'];
else $username = $string;
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0) $return = 0;
else $return = 1;
$stmt->close();
$DB->close();
return $return;
}
TABLES:
CREATE TABLE user
(
uid mediumint(6) unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(10) NOT NULL,
sex tinyint(1) unsigned NOT NULL default 1,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(5) NOT NULL,
province varchar(50) NOT NULL,
country tinyint(3) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
last_login TIMESTAMP,
registered TIMESTAMP,
online tinyint(1) unsigned default 0,
admin tinyint(1) unsigned default 0,
comment_allowed tinyint(1) unsigned default 0,
post_allowed tinyint(1) unsigned default 0
) ENGINE=InnoDB;
CREATE TABLE future_user
(
username varchar(15) NOT NULL,
password varchar(15) BINARY NOT NULL,
mail varchar(50) NOT NULL,
name varchar(50) NOT NULL,
surname varchar(50) NOT NULL,
birth char(8) NOT NULL,
sex tinyint(1) unsigned NOT NULL,
address varchar(50) NOT NULL,
city varchar(50) NOT NULL,
zip char(10) NOT NULL,
province varchar(50) NOT NULL,
country varchar(50) NOT NULL,
number1 varchar(50) NOT NULL,
number2 varchar(50) NOT NULL,
code char(10) NOT NULL
) ENGINE=InnoDB;
"SELECT *
FROM user u
LEFT JOIN future_user fu on fu.id = u.id
WHERE u.username=?
LIMIT 1"
With out seeing more of your table structure this what i can come up with.
This will select the user in future user too
You could do a CROSS JOIN to connect the two tables and query them that way
SELECT * FROM user JOIN future_user
WHERE user.username = ? OR future_user.username = ?
You'll probably need to tweak that * so that identically named columns in the two tables don't overlay each other.

Categories