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
Related
I am working on creating table in to my database with mysql and here is my code:
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL DEFAULT '',
`rating` tinyint(2) NOT NULL DEFAULT '0',
`proj_date` date NOT NULL DEFAULT '0000-00-00',
`proj_desc` text NOT NULL DEFAULT '',
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`emailid` varchar(100) NOT NULL DEFAULT '',
`customratings` varchar(100) NOT NULL DEFAULT '',
`photo_option` varchar(100) NOT NULL DEFAULT '',
`title` varchar(100) NOT NULL DEFAULT '',
`citation` varchar(100) NOT NULL DEFAULT '',
`date_option` varchar(100) NOT NULL DEFAULT '',
`rating_option` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);
But this is not reflecting into my database ? Why were I may be going wrong ?
but I tried creating other table with the following code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `setting` (
`id` int(11) NOT NULL auto_increment,
`script_url` text NOT NULL,
`date` varchar(4) NOT NULL,
`rateing` varchar(4) NOT NULL,
`photo` varchar(4) NOT NULL,
`dateformat` varchar(4) NOT NULL,
`page_limit` int(4) NOT NULL,
`proj_desc` varchar(4) NOT NULL,
`companyname` varchar(4) NOT NULL,
`text_color` varchar(255) NOT NULL,
`citation_color` varchar(255) NOT NULL,
`bg_color` varchar(255) NOT NULL,
`border_color` varchar(255) NOT NULL,
`ratingsformat` varchar(250) NOT NULL,
`rating` varchar(250) NOT NULL,
`customratings` varchar(250) NOT NULL,
`speed` varchar(250) NOT NULL,
`pagination` varchar(250) NOT NULL,
`version` varchar(250) NOT NULL,
`global_option` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0;
") or mysqli_error($link);
it is being created correctly and both the tables are in the same file
No you cannot create table using an insert statement.
There are four types of SQL statements:
DML (DATA MANIPULATION LANGUAGE)
DDL (DATA DEFINITION LANGUAGE)
DCL (DATA CONTROL LANGUAGE)
TCL (TRANSACTION CONTROL LANGUAGE)
DML is your SELECT, INSERT, UPDATE and DELETE statements...
DDL is you your CREATE, ALTER and DROP statements.
See more info about types of SQL statements
In order to insert data in your table, first you need to create it.
How to create sql table from php
No. "INSERT INTO" used to insert the data to existing table only.You should create the table with respective column before try to insert the values.
Or you can check the table exist or not before going insert."If exists" u can insert the value else just create and insert the values.
This worked for me but I don't know how?
I just removed DEFAULT '' present while creating review table and table just got created
Here is edited code
mysqli_query($link, "CREATE TABLE IF NOT EXISTS `review` (
`clients_id` int(15) NOT NULL AUTO_INCREMENT,
`client_id` varchar(150) NOT NULL,
`rating` tinyint(2) NOT NULL,
`proj_date` date NOT NULL,
`proj_desc` text NOT NULL,
`photoname` text NOT NULL,
`companyname` text NOT NULL,
`feedback` text NOT NULL,
`status` tinyint(1) NOT NULL,
`emailid` varchar(100) NOT NULL,
`customratings` varchar(100) NOT NULL,
`photo_option` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`citation` varchar(100) NOT NULL,
`date_option` varchar(100) NOT NULL,
`rating_option` varchar(100) NOT NULL,
PRIMARY KEY (`clients_id`),
FULLTEXT KEY `feedback` (`feedback`)
) ENGINE=MyISAM AUTO_INCREMENT=1") or mysqli_error($link);
So I'm running a PDO update working, and for some reason it won't update the table...
$business_id = 9874128;
$hidden = 1;
$query = "UPDATE business_property_overrides SET hidden=? WHERE business_id=?";
try {
$stmt = $pdo->prepare($query);
$stmt->execute(array($business_id, $hidden));
}
For some reason this won't update, even though I get no errors. The existing tables schema looks like this, and the data is:
There is an existing data set with business_id = 9874128 and hidden set to 0, but it won't update when I run the above code.
CREATE TABLE `business_property_overrides` (
`business_id` int(11) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(512) NOT NULL,
`apt_type` varchar(25) DEFAULT NULL,
`apt_num` varchar(9) DEFAULT NULL,
`street_address` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`state` varchar(255) DEFAULT NULL,
`zip` varchar(25) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`url` varchar(512) DEFAULT NULL,
`hours` varchar(100) DEFAULT NULL,
`openhours` varchar(100) DEFAULT NULL,
`location` point DEFAULT NULL,
`yelp` varchar(512) DEFAULT '0',
`twitter` varchar(512) DEFAULT '0',
`hidden` tinyint(1) DEFAULT '0',
`merged` int(11) DEFAULT NULL,
`closed` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `business_id` (`business_id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9874134 DEFAULT CHARSET=utf8;
The hidden is TINYINT 1 characters long, you are assigning it business_id which is 7 characters long, that is the error.
Change
$stmt->execute(array($business_id, $hidden));
To:
$stmt->execute(array($hidden,$business_id))
As I've already commented over here, or you can simply use the placeholders of taking no care about the occurence like as
$query = "UPDATE business_property_overrides SET hidden = :hidden WHERE business_id = :business_id";
try {
$stmt = $pdo->prepare($query);
$stmt->execute(array(":business_id" => $business_id, ":hidden" => $hidden));
}
I restarted the MySQL service and I attempted to use my PHP programs delete function to delete an existing row but I'm finding although the delete queries were counted the row was not deleted. I tried applying on delete cascade to the foreign key of the child table but that did not seem to have an effect. I'm wondering why the delete would be doing nothing.
CREATE TABLE `customers` (
`idcustomers` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(45) DEFAULT NULL,
`lastname` varchar(45) DEFAULT NULL,
`address1` varchar(45) DEFAULT NULL,
`address2` varchar(45) DEFAULT NULL,
`city` varchar(45) DEFAULT NULL,
`state` varchar(45) DEFAULT NULL,
`zip` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`cell` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idcustomers`),
UNIQUE KEY `idcustomers_UNIQUE` (`idcustomers`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=latin1
CREATE TABLE `events` (
`idevents` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(250) DEFAULT NULL,
`start` datetime DEFAULT NULL,
`end` datetime DEFAULT NULL,
`allday` varchar(50) DEFAULT NULL,
`url` varchar(1000) DEFAULT NULL,
`customerid` int(11) NOT NULL,
`memo` longtext,
`dispatchstatus` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idevents`),
KEY `FK_events` (`customerid`),
CONSTRAINT `FK_events` FOREIGN KEY (`customerid`) REFERENCES `customers` (`idcustomers`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=latin1
Com_delete 2
The PHP looks like this:
<?php
session_start();
date_default_timezone_set("America/Los_Angeles");
if($_SESSION['loggedin'] != TRUE)
{
header("Location: index.php");
}
require_once('../php.securelogin/include.securelogin.php');
$mysqli = new mysqli($ad_host, $ad_user, $ad_password, "samedaycrm");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$customerid = $_SESSION['customer_id'];
$tSQL = "delete from events where customerid = \"$customerid\"";
$result = $mysqli->query($tSQL);
$tSQL = "delete from customers where idcustomers = \"$customerid\"";
$result = $mysqli->query($tSQL);
echo $mysqli->error;
?>
Assuming that the customerid and idcustomers columns are both numeric it should be fine. You should not need to quote the variables in those queries btw, then you wouldnt need to escape them. You may try:
$tSQL = "delete from events where customerid = $customerid";
but it should not be any different than what you used already. Of course if you are not sure of the type of the column you can use:
$tSQL = "delete from events where customerid = '".$customerid."'";
or you can get away with:
$tSQL = "delete from events where customerid = '$customerid'";
but I have always hated that for some reason.
if all of that fails troubleshoot by spitting out the $customerid (or even the whole $tSQL) variable and then trying the query manually in phpmyadmin or toad or whatever db client you use, and see what it tells you. If it just says 0 rows affected, then run it like a select instead. Tailor to fit.
I have a database setup like
`id` int(11) unsigned NOT NULL auto_increment,
`ad-id` int(11) default NULL,
`advertiser-id` int(11) default NULL,
`advertiser-name` varchar(250) default NULL,
`advertiser-category` varchar(250) default NULL,
`buy-url` varchar(255) default NULL,
`catalog-id` varchar(255) default NULL,
`currency` varchar(3) default NULL,
`description` varchar(255) default NULL,
`image-url` varchar(255) default NULL,
`in-stock` varchar(255) default NULL,
`isbn` varchar(13) default NULL,
`manufacturer-name` varchar(255) default NULL,
`manufacturer-sku` varchar(50) default NULL,
`name` varchar(255) default NULL,
`price` decimal(10,2) default NULL,
`retail-price` decimal(10,2) default NULL,
`sale-price` decimal(10,2) default NULL,
`sku` varchar(50) default NULL,
`upc` varchar(50) default NULL,
I am trying to load the data like this:
LOAD DATA LOW_PRIORITY LOCAL INFILE "/home/datafeed/tempfile.csv" REPLACE INTO TABLE products_import FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY """" LINES TERMINATED BY "\n" (ad-id, advertiser-id, advertiser-name, advertiser-category, buy-url,catalog-id,currency, description,image-url,in-stock,isbn,manufacturer-name,manufacturer-sku,name,price,retail-price,sale-price,sku, upc);
but it doesn't seem to like database names with dashes in them. The field names are pretty much set in stone. If I try to insert without the field names it sets everything in the wrong field (starts with autoinc)
I'm not very good with MySQL any help would be appreciated.
Put back-ticks around the field names: `ad-id`, etc., like in your table structure listing.
My knowledge level here is like zilch, but please bear with me.
I have a site built in PHP/MySQL that uses the Smarty template engine. There's a registration form that, for some reason, isn't posting the data to the DB. Here's the function:
$u = new H_User;
$u->setFrom($p);
$smarty->assign('user', $u);
$val = $u->validate();
if ($val === true) {
$temp = new H_User;
$temp->orderBy('user_id desc');
$temp->find(true);
$next_id = $temp->user_id + 1;
$u->user_id = $next_id;
$u->user_password = md5($p['user_password']);
$u->user_regdate = mktime();
$u->user_active = 0;
$u->insert();
$hash = md5($u->user_email . $u->user_regdate);
$smarty->assign('hash', $hash);
$smarty->assign('user', $u);
$smarty->assign('registration_complete', true);
$d = new H_Demographic;
$d->setFrom($p);
$d->insert();
How can I figure out what's wrong here? I don't get any PHP errors and I don't know how to get MySQL to display the errors that might indicate what's wrong with that syntax.
MORE INFO AS PER REQUESTS
#
# Table structure for table `user`
#
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` mediumint(8) NOT NULL default '0',
`user_active` tinyint(1) default '1',
`username` varchar(25) NOT NULL default '',
`user_password` varchar(32) NOT NULL default '',
`user_session_time` int(11) NOT NULL default '0',
`user_session_page` smallint(5) NOT NULL default '0',
`user_lastvisit` int(11) NOT NULL default '0',
`user_regdate` int(11) NOT NULL default '0',
`user_level` tinyint(4) default '0',
`user_posts` mediumint(8) unsigned NOT NULL default '0',
`user_timezone` decimal(5,2) NOT NULL default '0.00',
`user_style` tinyint(4) default NULL,
`user_lang` varchar(255) default NULL,
`user_dateformat` varchar(14) NOT NULL default 'd M Y H:i',
`user_new_privmsg` smallint(5) unsigned NOT NULL default '0',
`user_unread_privmsg` smallint(5) unsigned NOT NULL default '0',
`user_last_privmsg` int(11) NOT NULL default '0',
`user_emailtime` int(11) default NULL,
`user_viewemail` tinyint(1) default NULL,
`user_attachsig` tinyint(1) default NULL,
`user_allowhtml` tinyint(1) default '1',
`user_allowbbcode` tinyint(1) default '1',
`user_allowsmile` tinyint(1) default '1',
`user_allowavatar` tinyint(1) NOT NULL default '1',
`user_allow_pm` tinyint(1) NOT NULL default '1',
`user_allow_viewonline` tinyint(1) NOT NULL default '1',
`user_notify` tinyint(1) NOT NULL default '1',
`user_notify_pm` tinyint(1) NOT NULL default '0',
`user_popup_pm` tinyint(1) NOT NULL default '0',
`user_rank` int(11) default '0',
`user_avatar` varchar(100) default NULL,
`user_avatar_type` tinyint(4) NOT NULL default '0',
`user_email` varchar(255) default NULL,
`user_icq` varchar(15) default NULL,
`user_website` varchar(100) default NULL,
`user_from` varchar(100) default NULL,
`user_sig` text,
`user_sig_bbcode_uid` varchar(10) default NULL,
`user_aim` varchar(255) default NULL,
`user_yim` varchar(255) default NULL,
`user_msnm` varchar(255) default NULL,
`user_occ` varchar(100) default NULL,
`user_interests` varchar(255) default NULL,
`user_actkey` varchar(32) default NULL,
`user_newpasswd` varchar(32) default NULL,
`first_name` varchar(40) NOT NULL default '',
`last_name` varchar(40) NOT NULL default '',
`level` int(10) unsigned NOT NULL default '0',
`disabled` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`user_id`),
KEY `user_session_time` (`user_session_time`)
) TYPE=MyISAM;
I'm still trying to figure this out and dump this in as a comment vs. an answer so I apologize if this shows up as an answer because it is not. Try putting the following code to spit out your errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
You may want to look at your php.ini file to allow displaying errors as well.
Do you have access to your server error log? That should show MySQL errors, I think. But as Pekka said, this isn't really enough info to go on.
MySQL connections all have a way to access the last errors thrown by them. It depends on which method you're using to connect to the DB. For instance, I use mysqli class. Therefore, as an example directly from PHP's website:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$mysqli->query("SET a=1")) {
printf("Errormessage: %s\n", $mysqli->error);
}
is how I could connect and then retrieve an error if it was thrown. How are you sending data to the DB? Do you have an example of the code that injects the data into the DB?
put
trigger_error(mysql_error());
after
$d->insert();
Edit:
As Marc B pointed out, you would need to use
trigger_error(mysqli_error());
instead for mysqli_ functions. PHP can be lame sometimes.