I am using SQL statements embedded in two PHP files to produce a database that appears in HTML as well as in phpMyAdmin. I have created a table like with the following command:
$sql = "CREATE TABLE WeatherCenter (OutgoingLongwaveRadiation VARCHAR(30))";
In the second PHP file, I have:
$sql = "ALTER TABLE WeatherCenter
ADD COLUMN (
`Barometric Pressure` SMALLINT NOT NULL,
`CloudType` VARCHAR(70) NOT NULL,
`WhenLikelyToRain` VARCHAR(30) NOT NULL);";
When I execute the files, I keep getting "Undefined column Barometric Pressure does not exist in filed list". I realized that this is because somewhere else in my PHP file I listed the variable as BarometricPressure and not Barometric Pressure (ie. one has a gap, and the other doesn't). When I corrected the mistake in the ALTER TABLE by deleting the gap, the same error message STILL appeared in the phpMyAdmin database. It seems to me that changing the name of the field in the PHP file does NOT change it in the phpMyAdmin database. As a result, no data is being transmitted to the database.
Could someone tell me if I changed the syntax of the above to
$sql = "ALTER TABLE WeatherCenter
ADD COLUMN `Barometric Pressure` SMALLINT NOT NULL AFTER `OutgoingLongwaveRaadiation`,
ADD COLUMN `CloudType` VARCHAR(70) NOT NULL AFTER `BarometricPressure`,
ADD COLUMN `WhenLikelyToRain` VARCHAR(30) NOT NULL AFTER `CloudType` ;";
will the problem go away? I mean, do you HAVE to use an "ADD COLUMN" before EACH field name, and do you HAVE to specify the "AFTER previous field name"? Do you have to take these additional measures to ensure that any mistake in the field name that appears in the phpMyAdmin can be erased by rewriting your code in the PHP file? Could someone simply tell me what the correct syntax is please, because there appears to be inconsistencies. Some of the ALTER TABLE statements do not have opening and close brackets and no backticks, but other ALTER TABLE statements make it clear that you must have opening and closing brackets and backticks such that the last few characters in the ALTER TABLE statement MUST be );";
I am throughly confused.
Related
I'm having an odd issue where creating a table adds the back ticks to the table name in the database.
public function create_table($name)
{
$sql = "
CREATE TABLE IF NOT EXISTS `?` (
id int(11) NOT NULL AUTO_INCREMENT,
url varchar(255) NOT NULL,
resolved tinyint(1) NOT NULL,
PRIMARY KEY (id)
)";
$query = $this->_pdo->prepare($sql);
$query->bindValue(1, $name);
if($query->execute())
{
print("Created");
}
else
{
var_dump($query->errorInfo());
}
}
The reason I am doing it like that and binding the $name is that it will be done dynamically by a web crawler I'm making to look for common file and directory names and due to the large amounts of paths gatherable ive decided on a table for each site and its name generated from its hostname. (Example of a possible dodgy hostname: https://whe.re/)
But this has led to this.
So I tried without them and it throws an error
"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''random_site'
What am I not seeing or thinking, it's been a while since I've used PHP and I'm at a loss as all my searches lead me to why table names should be surrounded with back ticks when making a query which isn't my issue.
Thanks
Info: MariaDB
PHP: 7.4.6
That's because your are binding a string value, so it is injected with surrounding single quotes. But bottom line, you just can't pass a table name as a parameter in the query. The binding mechanism is meant to pass literal values, which obviously a table name is not.
In this specific situation, you don't have another choice than string concatenation:
$sql = "
CREATE TABLE IF NOT EXISTS `$name` (
id int(11) NOT NULL AUTO_INCREMENT,
url varchar(255) NOT NULL,
resolved tinyint(1) NOT NULL,
PRIMARY KEY (id)
)";
$query = $this->_pdo->prepare($sql);
if ($query->execute()) {
...
} else {
...
}
This implies that you need to throughly validate the variable on application side before passing it to the query, which is not an easy task.
This ultimately raises the question of why you would have a separate table for each site. I would not recommend this design, which violates the basic normalization rules, and can quickly turn to a maintenance nightmare. Instead, you should have a reference table that lists the sites, and a single table for all paths, with a foreign key column that references the sites table. With proper schema and indexing, you are not likely to experience performance issues, unless you have zillions of rows (in which case other options are available, such as logical partitioning).
is it possible adding a column into a database table after an insert?
If yes kindly give me an example code for it i don't know how to make of it
yes it is possible for example :
CREATE TABLE my_table (
id integer(10),
fname varchar(50) );
and insert the values :
INSERT INTO `my_table`(`id`, `fname`) VALUES (1,'edverd');
see the value is added here
NOW Alter the Table
ALTER TABLE my_table ADD COLUMN lname varchar(50);
see the table is altered here
but the values in the added column will be null for every row present in that table.
now you can simply add the values in the added column
INSERT INTO `my_table`( `lname`) VALUES ('cullen');
To Answer Your Question:
Yes you totally can.Just an FYI
Insert Is basically Creating a Brand New row.(If there is something already present in the row You use UPDATE)
to add Column to the database the syntax remains the same, if you are using mysql this is something your code should look like
$query="ALTER TABLE Users ADD COLUMN PASSWORD VARCHAR(100)";
$result= $mysqli->query($query);
if(!$result) echo "Failed to Add column TO The database";
BUT:
1.What you are trying to do isn't a good practice.
2.Read More about Php, You can get a course on udemy or just buy books on Php one of which is Learning PHP MYsql and Javascript By Robin Nixon, or just read more from the php manual, or mysql manual.
3.Nobody is Rude here, but lack of effort is something nobody appreciates.
4.Lastly don't get disheartened,Work Hard
I can't insert any rows into my database, and the error I'm getting is:
This doesn't make any sense as it was working fine before, nothing has changed as far as I know. The ID field is set to primary, not null and auto increment:
I was able to insert a row manually through PHPMyAdmin. Heres the code I'm inserting with:
$query = "INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES (?,?,?,?,?)";
$stmt = $ngdb->prepare($query);
$file_id = $this->fileID;
$snp_id = $row['id'];
$genotype = $this->formatGenotype($extractedGenotype);
$zygosity = $this->assignZygosity($genotype,$minor_allele);
$reputation = $this->assignReputation($zygosity,$genotypes);
$stmt->bind_param("sssss", $file_id,$snp_id,$genotype,$reputation,$zygosity);
$stmt->execute();
I tried deleting the table and creating a new table but it didn't fix it. Is there anything else I can do to try and diagnose and fix this?
make sure for this line:
$stmt->bind_param("sssss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
First parameter of bind_param() you used is "sssss" that means all off data is string. Please fix it as the right type data of your type on table database.
Please use "i" for integer. For example:
$stmt->bind_param("iisss",
$file_id,$snp_id,$genotype,$reputation,$zygosity);
I make the code above as an example because I can not see all of your table descibe.
I tried inserting with the WordPress database connection:
$wpdb->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('$file_id','$snp_id','$genotype','$reputation','$zygosity')");
and it works, but if I try using an identical query with my own database connection:
$db = new mysqli('localhost', NG_DB_USER, NG_DB_PASS, NG_DB_NAME);
$db->query("INSERT INTO wp_genomics_results (file_id,snp_id,genotype,reputation,zygosity) VALUES ('111','$snp_id','$genotype','$reputation','$zygosity')");
I get the same error:
Error No: 1364 - MySQL error Field 'id' doesn't have a default value
I don't understand why it works with wordpress but not my own database connection. I went into my mysql.ini file and changed this:
sql-mode="STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ZERO_DATE,
NO_ZERO_IN_DATE,NO_AUTO_CREATE_USER"
to this:
sql-mode=""
and now I can insert a row, the error stopped happening. I still don't understand why this error was occuring to begin with. And now theres a new error happening:
Duplicate entry '0' for key 'PRIMARY'
I don't understand it because the id column is set to auto increment. Theres also no rows in there with ID = 0. I even emptied the table to make absolute sure there is no row in there with ID = 0. I'm very confused about whats happening. Heres the output of the table structure:
> mysql> SHOW CREATE TABLE wp_genomics_results;
| wp_genomics_results | CREATE TABLE `wp_genomics_results` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
`file_id` int(11) NOT NULL,
`snp_id` int(11) NOT NULL,
`genotype` varchar(3) NOT NULL,
`reputation` varchar(3) NOT NULL,
`zygosity` int(3) NOT NULL,
PRIMARY KEY (`id`),
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+---------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
I notice it says 1 row in set, but the table is actually empty. And once again, I'm able to insert a new row through PHPMyAdmin:
Oh God I feel like an idiot. All this time, the problem was that I had the wrong database selected. So it was querying a table from a different database, and this tables ID field didn't have auto increment set. Ah well, it was a good learning experience, getting to know MySQL better.
EDIT
The table definition looks really strange. It looks like there's a second index on the id column. The id column is already defined as the PRIMARY KEY.
It's this line in the table definition that is bothers me...
KEY `id` (`id`)
It's bizarre that MySQL would even let you add a second index on the same column, and not return an error like "such an index already exist" or "the set of columns is already indexed" or such.
I recommend you run a statement to drop the index named id. Execute either
DROP INDEX `id` ON `wp_genomics_results`;
-or-
ALTER TABLE `wp_genomics_results` DROP KEY `id`;
It's possible that this index was contributing to the issue.
ORIGINAL ANSWER
I suggest you figure out exactly which statement is throwing an error.
I suspect it's not the execution of INSERT INTO wp_genomics_results statement.
If it were me, I'd take a look at the assignZygosity and assignReputation functions. I suspect the culprit is in down in there.
I suspect there's something going on in those functions. My guess (just a guess) is that one of those functions is performing a lookup to get a value for a foreign key. And, if a foreign key value isn't found, something is being executed to INSERT a row into the referenced table. There must be some reason that function is being called, some reason we're not just using the value supplied as a parameter...
The formatGenotype function is also a suspect, by proximity. (I'm less a-feared of that function name... but again, I have no idea what that function is doing.)
If that's not the issue, if it's really the execution of the INSERT statement shown in the code, then I'd look for a "BEFORE INSERT" trigger on the wp_genomics_results table... maybe the trigger is performing an insert to some other table.
As a quick test, I'd comment out the calls to those functions, and just assign a literal values to $zygosity and $reputation.
I want to know the exact line number in the exact file where the error is being thrown.
I also want the complete error message from MySQL.
Following every execution of a database interaction, I want to check the return, and if there's an error, I want (for debugging purposes) a unique message that indicates where we are in the code when the error is thrown, along with the complete error message returned from MySQL (mysqli_error).
I'm not going to just assume, without evidence, that it's the execution of this particular statement that's causing the error.
And if it really is this statement, then we'd need to take a look at the actual MySQL definition of the table... the output from a SHOW CREATE TABLE wp_genomics_results statement.
And we want to make sure that we are looking at the same MySQL instance and database that the code is connecting to, and not some other MySQL instance or database.
I have a 'code_number' column with varchar(25) field type, and I make it into Unique field type. I try to insert 2 number to the number column with different number. First number is '112225577' and for the second number is '112228899'. Now I'm trying to update the first number, and only change 3 last digit number '577' with '433', became '112225433'. But I got error Duplicate entry '112225433' for key 'code_number'.
How can it be duplicate? I only have 2 data and the data is not same. Can anybody explain to me why this happening?
UPDATE
here is my code.
Product
id INT(11)
product VARCHAR(250)
code_number VARCHAR(25) UNIQUE
...
Account
id INT(11)
name VARCHAR(250)
email VARCHAR(100) UNIQUE
...
And my query is like this:
$this->db->set('code_number','112225433');
$this->db->where('code_number','112225577');
$this->db->update('product');
Same problem goes to email column when i try to update account record.
here is the code sample:
$this->db->set('email','andy123#yahoo.com');
$this->db->where('name','Andy');
$this->db->update('account');
the email data in email column where name='Andy' is 'andy123#hotmail.com'.
You can definitely do this without a problem (see the SQL Fiddle here).
I imagine that you are doing something where both rows are getting updated to the same value, the equivalent of:
update t
set code_number = '112225433';
This will generate exactly the error you report. There are, no doubt, many SQL queries that would have this effect. But, this would generate such an error.
It could be a problem with your SQL editor. For instance, it could show you the previous value but it could have update it already, so that you you believe that it has not been changed yet. I ever had such problem like this before: the value was updated in the DB but the editor had no updated yet.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get Insert Statement for existing row in MySQL
Lets say we have a table called users:
CREATE TABLE IF NOT EXISTS users(
UID int(11) PRIMARY KEY NOT NULL auto_increment,
fname varchar(100) default NULL,
lname varchar(100) default NULL,
username varchar(20) default NULL UNIQUE,
password blob
)ENGINE=InnoDB DEFAULT CHARSET=utf8
Lets assume there's a few rows filled up in the table.
I know there is a query that returns the creation of the table -> SHOW CREATE TABLE users
But I'm looking to recreate individual insert statements to save them in a log...I know this sounds weird, but I am making a custom CMS where everything is logged, and hopefully where updated/deleted rows could rollback at point in time...therefore I would need to recreate exact insertion query from table data (I have searched all over the web for an answer and can't find it...)
Is there a query that would return "automatically" the query that inserted that specific row by primary key?
I am looking for a query that would do this:
SHOW INSERT FROM users WHERE PRIMARY_KEY=2
Returns:
INSERT INTO users (UID,fname,lname,username,password) VALUES (2,'somename','somelastname','someusername','someAESencryptedPassword')
The reason I'm thinking such a query would exist/be possible is because when you backup a database with php myadmin (cpanel) and you open the file, you can actually view each insert to recreate the table with all rows a that point in time...
There is no such "command" (the data is stored, but not the actual SQL that inserted it), and it wouldn't make sense to do what you're asking. You do realize your "log" would be about 20 times larger (at least) than the actual table and data itself? And it's not going to able to retrieve the INSERT statement without a lot of work to track it down (see the comments below) anyway.
Study transactional SQL, make use of server logging and transactions, and back up the data regularly like you're supposed to and quit trying to reinvent the wheel. :-)
There is no such command to retrieve the original insert statement. However, you can always remake the insert statement based on the existent table structure and data.
The following link may help you, where this has already been asked:
Get Insert Statement for existing row in MySQL
Another possible option is using mysqldump with php to export the data as SQL statements.