Mysql update all columns starting with same Name - php

I have a dynamic table named 'products' with multiple Languages.
The table columns looks like this:
id, product_id, store_de, store_en, store_fr, store_es... etc
The languages can be more or less.
Now I want to update this table and set all columns beginning with "store_" to value 1.
I tried the following:
$stmt = $dbh->prepare( "UPDATE products SET `store_%` = ? WHERE product_id = ?" );
$stmt->execute( array( 1, $lastID ) );
I get following error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'store%' in
'field list'
Is there a way to update all columns beginning with 'store_' or do I have to list all the columns?
Based on the answer from jekaby here is the full solution that worked for me:
$get_stores = $dbh->prepare("SHOW COLUMNS FROM products_active WHERE field REGEXP '^store'");
$get_stores->execute();
$stores = $get_stores->fetchAll();
$update_string = "";
$first_store = true;
foreach($stores as $store) {
if(!$first_store) {
$update_string .= ", ";
} else {
$first_store = false;
}
$update_string .= $store['Field']." = '".$status."'";
}
$update_activity = $dbh->prepare("UPDATE products_active SET $update_string WHERE product_id = ?");
$update_activity->execute(array($product_id));

You need to set each column explicitly. SQL doesn't support wildcards for column names (with the exception of * for SELECT *):
update products
set store_de = 1,
store_en = 1,
store_fr = 1,
store_es = 1,
. . .
where product_id = ?;
Your data structure suggests that you really want a ProductStores table. This would have one row per language (?) and per product. It would have at least three columns:
ProductId
Language
Value
Then you would simply do:
update ProductStores
set Value = 1
where ProductId = ?;

You can not do like this store_% - it is nonexistent column in table as it is written in your error.
You should get all colums with names like /^store_/ (regexp). And than update all this fields having listed them.
mysql> SHOW COLUMNS FROM products where field REGEXP '^store_'
Than collect all fields from 'Field'... You can read more how to get all columns here.

Related

INSERT / UPDATE Mysql Single Form

I have 2 database tables
tbl1 users ---------- tbl2 gamesystems
uid field ------------- gs_uid field
the 2 tables are tied together by the user_id..
now i want tbl2 to only be updated able and fields are not required.. with the exception of the gs_uid when they update there system.
my only issue is i need to insert the user_id into the gs_uid.
function game_system()
{
if(isset($_POST['game_system'])) {
$user_id = $_SESSION['uid'];
$motherboard = escape($_POST['motherboard']);
$processor = escape($_POST['processor']);
$memory = escape($_POST['memory']);
$graphics = escape($_POST['graphics']);
$harddrive = escape($_POST['harddrive']);
$power = escape($_POST['powersupply']);
$cooling = escape($_POST['cooling']);
$towercase = escape($_POST['towercase']);
$sql = "INSERT INTO gamesystem(gs_uid, motherboard, processor, memory, graphics, harddrive, powersupply, cooling, towercase) ";
$sql .= "VALUES('{$user_id}','{$motherboard}','{$processor}','{$memory}','{$graphics}','{$harddrive}','{$power}','{$cooling}','{$towercase}') ";
$result = query($sql);
}
}
If gs_uid is the primary key of table 'gamesystem' , then this field should not accept empty data.
Otherwise, if gs_uid is NOT the key, what's the primary key of this table? In case of UPDATE, you'll need to specify which row you'd like to update, otherwise the system will not know how to do so.
the SQL should looks like below
UPDATE "gamesystem"
SET "gs_uid" = $user_id
WHERE YOUR_PRIMARY_KEY_COLUMN = SPECIFIC VALUE;

SQLite 3 , duplicate a row and change only one field

I have some table in my SQLite3 database , for example
table1
table2
table3
All tables have a field called id (integer NOT NULL PRIMARY KEY UNIQUE) (not auto increment)
My goal is to duplicate a record of one of these tables, changing only the id field (with a new id). I would like to do this without having to know the name of all the columns in each table.
I tried this solution, it works, but in this way i have to know the names of all columns
INSERT INTO table1 (id,column1,column2,column3)
SELECT NEWID,column1,column2,column3 FROM table1
WHERE id = OLDID
I tried also the method to create a temporary table, but without success
I have to run a query like this PRAGMA table_info(table1) , save the columns's name in an array , and then run a query created with a cycle ?
thanks
My solution
$TABLENAME = "mytablename";
$ID = 1423659222480;
$NEWID = 1423659222481;
$db = new PDO('sqlite:db.sqlite3');
$result_columns = $db->query("PRAGMA table_info(".$TABLENAME.")");
$appColumns = array();
$appColumns2 = array();
foreach ($result_columns as $row) {
array_push($appColumns, $row["name"]);
if($row["name"] != "id") array_push($appColumns2, $row["name"]);
}
$appColumns = implode(",",$appColumns);
$appColumns2 = implode(",",$appColumns2);
$appColumnsWithoutID = $NEWID.",".$appColumns2;
$queryDuplicate = "INSERT INTO ".$TABLENAME." (".$appColumns.") SELECT ".$appColumnsWithoutID." FROM ".$TABLENAME." WHERE id = ".$ID;

SQL query to alter table column names

I am running this SQL Query in PHP:
$sql="alter table callplandata change '".$_POST["col_name$y"]."' '".$_POST["col_newname$y"]."' ";
to alter column names but before it updates i want to check if the column name already exists and if it does to add a number on the end otherwise to just carry on updating
how can i do this using PHP?
Please, please, please, don't do this. This is about as unsafe a thing to do. However, I will say this: The ALTER TABLE syntax is worth a look:
ALTER TABLE <table name>
CHANGE [COLUMN] old_col_name new_col_name column_definition
Note that the column_definition bit is not optional.
Also, if you want to see if the fieldname given already exists:
SHOW COLUMNS FROM <table_name> /* or SHOW COLUMNS IN tbl */
Then, in PHP, depending on the extension you used, you do something like this:
$existingFields = array();
foreach ($resultSet as $row)
{
$existingFields[] = $row['Field'];
}
SHOW COLUMNS will also give you information concerning the type of each field, if it's a key, or even if it's an auto_increment value details, as ever, on the mysql website
So putting it all together:
$db = new PDO();//connect
$stmt = $db->prepare('SHOW COLUMNS IN callplandata WHERE Field = :field');
$bind = array(
':field' => $_POST['colname_new']
);
$stmt->execute($bind);
if ($row = $stmt->fetch())
throw new InvalidArgumentException($_POST['colname_new'].' already exists!');
$bind[':field'] = $_POST['colname_old'];
$stmt->closeCursor();//reset cursor, so we can re-use the statement
$stmt->execute($bind);//re-use statement
if (!($row = $stmt->fetch(PDO::FETCH_OBJ))
throw new InvalidArgumentException($_POST['colname_old'].' does not exist, cannot rename it!');
//very basic column definition construction here, needs more work, though!
$current = '';
$current = $row->Type. ' '.($row->Null == 'NO' ? 'NOT NULL ' : '').
($row->Default !== '' ? 'DEFAULT '.$row->Default.' ' : '').$row->Extra;
/**
* ADD CODE HERE TO SANITIZE THE NEW COLUMN NAME
* if you want to procede with this madness... I would urge you not to, though!
*/
$pdo->exec(
'ALTER TABLE callplandata
CHANGE '.$_POST['colname_old'].' '.$_POST['colname_new'].' './/rename
$current//add column definition
);
Disclaimer:
The code I posted here is meant to be purely academic. It should not be used, it's unsafe and incomplete. Please rethink what you are trying to do. Avoid, at all cost, using user data to alter how the server stores/structures the data!
Try this
SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'
In PHP
$result = mysqli_query("SHOW COLUMNS FROM `table` LIKE 'fieldname'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
I think you need to specify datatype and default value also.
example
ALTER TABLE `ca_4_4_14` CHANGE `active` `is_active` ENUM('Y','N') CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT 'Y' NOT NULL;

Update a whole column instead of a row

Ok is there a possibility to update a column instead of a row?
f.e something like that:
$laninpstmt = $db->prepare ("UPDATE table SET column_name WHERE id = :allids");
$laninpstmt->bindParam(':allids', $_POST['input0']);
$laninpstmt->bindParam(':allids', $_POST['input1']);
$laninpstmt->bindParam(':allids', $_POST['input2']);
$laninpstmt->bindParam(':allids', $_POST['input3']);
$laninpstmt->bindParam(':allids', $_POST['input3']);
If i explain the code it's like:
Update all the rows(allids) from one column in a table
Running your query without a where clause will update all rows, and if you update a single field it will be the same as updating a column
UPDATE `test` SET `field_5` = 7
Will update table test and set all values in the column field_5 to 7
You could use IN:
Apparently, you need to do your own query, see https://stackoverflow.com/a/920523/2575355.
$inputs = array($_POST['input0'], $_POST['input1'], $_POST['input2']);
$allids = implode(', ', $inputs)
$laninpstmt = $db->prepare ("UPDATE table SET column_name WHERE id IN ($allids)");
You forgot to specify the value for you column_name like that
UPDATE table SET column_name = 'Some_value here' WHERE id = :allids
i guess you want do this
$laninpstmt = $db->prepare ("UPDATE table SET column_name = Concat(:allids1 , :allids2, :allids3, :allids4) WHERE id = :allids");
$laninpstmt->bindParam(':allids', $_POST['input0']);
$laninpstmt->bindParam(':allids1', $_POST['input1']);
$laninpstmt->bindParam(':allids2', $_POST['input2']);
$laninpstmt->bindParam(':allids3', $_POST['input3']);
$laninpstmt->bindParam(':allids4', $_POST['input4']);

Take Row from Table1 and create or update Column from Table2

I'd like to make a table with row entries that define columns in another Table. This way I can easily update the tables later on if the questions for a form are changed or added.
Eg.
Table1: Questions
Question column_name column_type characters default
What is your name? name Char 255 ''
When where you born? birth char 255 ''
What is today's date? date int ''
Do you have a pet? pet bin 0
Table2: Results
name birth date
Cammy Teaneck 1988
Tommy Tenefly 2001
Tasha Brooklyn 1950
In the php form, check to see if all columns exist, if not create them in table2 and then add entry
$collect = db_query("SELECT column_name FROM {Table1}");
while ($data = db_fetch_array($collect)){
$name = $data['column_name'];
$stretch = db_query("SELECT $name FROM {Table2}");
if ($stretch == null or false){
UPDATE TABLE Table2 ($name $type($char) DEFAULT $default)
}
}
The pseudocode for what you are asking for is as follows:
foreach column in table1 {
$res = query("select column from table2");
if( ! $res ) {
query("alter table add field datatype(size) to table 2");
}
}
Heres a crude implementation, from where I got the idea from:
http://forums.phpfreaks.com/topic/193330-alter-table-add-column-if-not-exists-possible/
Please use information schema in mysql to check
whether this table contain this field or not
you can Find table name in information_schema this
use Like this
SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME='Table2' and COLUMN_name IN ('name','birth','date')
Please try this

Categories