Create table of BBDD #variable - php

I would like to create a Table in a BBDD by variable in MYSQL. The problem i have is that the code doesn't work and I am not sure why.
$variable = "xxx_'".$_POST['idtour']."'_xxxx";
// Create the table
$sql = "CREATE TABLE $tourname (
id_leg VARCHAR(3) NOT NULL COMMENT 'Identificación de la leg del tour, en orden')";
//The action
mysqli_query($link,$sql) or die("Error ".mysqli_error());
I think is a problem with the "_".Any help will be fantastic.

The problem isn't the _. It's the '. "xxx_'".$_POST['idtour']."'_xxxx" will result in xxx_'value'_xxxx, as a possible table name, and ' is not valid in a table name. If you MUST include invalid characters, then you'll need to use the backtick operator.
$tablename = "`xxx_'".$var."'_xxxx`";
That should get you further towards your goal.
On a side note: creating a table based on a user-provided variable is a bad idea. It risks users being able to create some bizarre and destructive behavior, and very often it's better accomplished by adding a column to an existing table. Have you tried adding a column user_idtour?

Related

How to add a possble value to a MySQL SET type in php, without know the current values

Hi everybody and sorry for my english.
I have the column "example" that is a SET type.
I have to make a php page where you can add values to that column.
First of all I need to know what is just in "example", to prevent the adding of an existing value by a control. Second of all I need to add the new value.
Here's what I had thinked to do.
//I just made the connection to the db in PDO or MySQLi
$newValue=$_POST['value']; //I take the value to add in the possible values from a form
//Now I have to "extract" all the possible values. Can't think how.
//I think I can store the values into an array
$result=$sql->fetch(); //$sql is the query to extract all the possible values from "example"
//So now i can do a control with a foreach
foreach($result as $control){
if ($newValue == $control){
//error message, break the foreach loop
}
}
//Now, if the code arrives here there isn't erros, so the "$newValue" is different from any other values stored in "example", so I need to add it as a possible value
$sql=$conn->query("ALTER TABLE 'TableName' CHANGE 'example' 'example' SET('$result', '$newValue')"); //<- where $result is the all existing possible values of "example"
In PDO or MySQLi, it's indifferent
Thanks for the help
We can get the column definition with a query from information_schema.columns
Assuming the table is in the current database (and assuming we are cognizant of lower_case_table_names setting in choosing to use mixed case for table names)
SELECT c.column_type
FROM information_schema.columns c
WHERE c.table_schema = DATABASE()
WHERE c.table_name = 'TableName'
AND c.column_name = 'example'
Beware of the limit on the number of elements allowed in a SET definition.
Remove the closing paren from the end, and append ',newval').
Personally, I don't much care for the idea of running an ALTER TABLE as part of the application code. Doing that is going to do an implicit commit in a transaction, and also require an exclusive table / metadata lock while the operation is performed.
If you need a SET type - you should know what values you add. Otherwise, simply use VARCHAR type.

PHP/PostgreSQL database writing issue

I'm having problems writing data from a form to multiple datatables on my PostgreSQL database.
Here is my data model
CREATE TABLE institutions(i_id PK, name text, memberofstaff REFERENCES staff u_id);
CREATE TABLE staff(u_id PK, username text, password text, institution REFERENCES institutions i_id);
So its a 1:1 relationship. These tables have been set up fine. It's the PHP script I'm having difficult with. I'm using CTE-datamodifying or at least trying to but I keep receiving errors on submit.
The PHP:
$conn = pg_connect('database information filled out in code');
$result = pg_query("WITH x AS (
INSERT INTO staff(username, password, institution)
VALUES('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING u_id, i_id)
INSERT INTO institutions (i_id, name, memberofstaff)
SELECT x.i_id, x.u_id, '$institution'
FROM x");
pg_close($conn);
So that's the code and the error I get is:
Warning: pg_query() [function.pg-query]: Query failed: ERROR: relation "institutions_i_id_seq" does not exist LINE 3: VALUES('AberLibrary01', '', nextval('institutions_i_id_se... ^ in DIRECTORY LISTING(I replaced this) on line 22
Anyone got any ideas?
Did you actually create the table with the column types of institutions.i_id and staff.u_id set to serial? Or create the sequence manually?
If the former, you don't need to explicitly use nextval anyway. If the latter, double-check the sequence name.
This would ideally be a comment, but I think it might have something to do with:
$'password' which should be '$password' on the fourth line of that example.

CREATE TABLE fails when i use an integer name for column

I'm trying to create a dynamic form builder. Therefore PHP gets a set of names from a database and creates a new table with those names as column names. This works quite well until one or more names are integer (for ex. '12345'). Then the script fails.
How can I force PHP of MySQL to give numeric table names?
Here is a piece of the code (its still a draft):
$slaop = 'id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id)';
require_once 'dbconnect.php';
$connector = new DbConnector();
$result = $connector->query( 'SELECT * FROM '.$form.' ORDER BY rang' );
while ($opslaan = $connector->fetchArray($result)){
$slaop .= ', ';
$slaop .= $opslaan['tekstid'];
$slaop .= ' TEXT';
}
echo $slaop;
// OPSLAAN
$formnaam = $_GET['welkform'];
require_once 'dbconnectsave.php';
$connector = new DbConnectorSave();
$connector->query('CREATE TABLE '.$formnaam.'('.$slaop.')')
or die(mysql_error());
$opslaan['tekstid']; is the part where the text of integer are called.
Does anyone have an idea?
Why not prefix all tables with the form name? Then integers don't matter...
As others have noted, this may not be a good idea.
However, you can still do it if the column name is surrounded in backticks. Here's a couple of MySQL examples:
create table abc (id int, 123 int); -- fails
create table abc (id int, `123` int); -- succeeds
How can i force php of mysql to give numeric table names?
May be you can force your application not to use such field names?
And also change the whole design as well, without employing dynamically created tables, and use more usual approach of storing table structure in some table?
Use a prefix that starts with a letter for your column names.

Using triggers / routines with table prefixes in mysql

I'm used to use mysql table prefixes in my php scripts. Yet triggers and routines sometimes are very useful too. Ok. Let's say i have a table: 'pre_customers'. And a procedure sth like
CREATE FUNCTION `get_all_clients`() RETURNS int(11)
BEGIN
DECLARE sum INT ;
SELECT COUNT(id) INTO sum FROM pre_customers ;
RETURN sum;
END
No big deal, just for example. And there is also a constant
<?php
define( 'DB_PREFIX', 'pre_' ) ;
It's being used for changing table prefixes. If i need to make an sql-request in the script i make it like this
$query = "SELECT * FROM " . DB_PREFIX . "customers" ;
$result = mysql_query( $query ) ;
...
Alright, but if i want to change this prefix in the php-script along with the table names it's gonna ruin all stored routines and triggers, they still will apply to 'pre_customers' table. So the question is is there a common practice how normally programmers solve this problem.
So the question is is there a common practice how normally programmers solve this problem.
Create a dump
Create some kind of template using that dump, with pre_ replaced with %db_prefix%
When you need to change prefix - replace prefix in the template and import it to mysql

Cannot simply use PostgreSQL table name ("relation does not exist")

I'm trying to run the following PHP script to do a simple database query:
$db_host = "localhost";
$db_name = "showfinder";
$username = "user";
$password = "password";
$dbconn = pg_connect("host=$db_host dbname=$db_name user=$username password=$password")
or die('Could not connect: ' . pg_last_error());
$query = 'SELECT * FROM sf_bands LIMIT 10';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
This produces the following error:
Query failed: ERROR: relation "sf_bands" does not exist
In all the examples I can find where someone gets an error stating the relation does not exist, it's because they use uppercase letters in their table name. My table name does not have uppercase letters. Is there a way to query my table without including the database name, i.e. showfinder.sf_bands?
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH in the shell or include_path in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
I had problems with this and this is the story (sad but true) :
If your table name is all lower case like : accounts
you can use: select * from AcCounTs and it will work fine
If your table name is all lower case like : accounts
The following will fail:
select * from "AcCounTs"
If your table name is mixed case like : Accounts
The following will fail:
select * from accounts
If your table name is mixed case like : Accounts
The following will work OK:
select * from "Accounts"
I dont like remembering useless stuff like this but you have to ;)
Postgres process query different from other RDMS. Put schema name in double quote before your table name like this, "SCHEMA_NAME"."SF_Bands"
Put the dbname parameter in your connection string. It works for me while everything else failed.
Also when doing the select, specify the your_schema.your_table like this:
select * from my_schema.your_table
If a table name contains underscores or upper case, you need to surround it in double-quotes.
SELECT * from "Table_Name";
I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this
$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"
This is realy helpfull
SET search_path TO schema,public;
I digged this issues more, and found out about how to set this "search_path" by defoult for a new user in current database.
Open DataBase Properties then open Sheet "Variables"
and simply add this variable for your user with actual value.
So now your user will get this schema_name by defoult and you could use tableName without schemaName.
You must write schema name and table name in qutotation mark. As below:
select * from "schemaName"."tableName";
I had the same issue as above and I am using PostgreSQL 10.5.
I tried everything as above but nothing seems to be working.
Then I closed the pgadmin and opened a session for the PSQL terminal.
Logged into the PSQL and connected to the database and schema respectively :
\c <DATABASE_NAME>;
set search_path to <SCHEMA_NAME>;
Then, restarted the pgadmin console and then I was able to work without issue in the query-tool of the pagadmin.
For me the problem was, that I had used a query to that particular table while Django was initialized. Of course it will then throw an error, because those tables did not exist. In my case, it was a get_or_create method within a admin.py file, that was executed whenever the software ran any kind of operation (in this case the migration). Hope that helps someone.
In addition to Bill Karwin's answer =>
Yes, you should surround the table name with double quotes. However, be aware that most probably php will not allow you to just write simply:
$query = "SELECT * FROM "SF_Bands"";
Instead, you should use single quotes while surrounding the query as sav said.
$query = 'SELECT * FROM "SF_Bands"';
You have to add the schema first e.g.
SELECT * FROM place.user_place;
If you don't want to add that in all queries then try this:
SET search_path TO place;
Now it will works:
SELECT * FROM user_place;
Easiest workaround is Just change the table name and all column names to lowercase and your issue will be resolved.
For example:
Change Table_Name to table_name and
Change ColumnName to columnname
It might be silly for a few, but in my case - once I created the table I could able to query the table on the same session, but if I relogin with new session table does not exits.
Then I used commit just after creating the table and now I could able to find and query the table in the new session as well. Like this:
select * from my_schema.my_tbl;
Hope this would help a few.
Make sure that Table name doesn't contain any trailing whitespaces
Try this: SCHEMA_NAME.TABLE_NAME
I'd suggest checking if you run the migrations or if the table exists in the database.
I tried every good answer ( upvote > 10) but not works.
I met this problem in pgAdmin4.
so my solution is quite simple:
find the target table / scheme.
mouse right click, and click: query-tool
in this new query tool window, you can run your SQL without specifying set search_path to <SCHEMA_NAME>;
you can see the result:

Categories