This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
Here is the situation. I just know total number of columns the table test_table has but don't know their names(sounds strange but its true). Is there any way I can write UPDATE Query for all column values on basis of some ID(auto-increment primary key)?
To add row in this table, I did following which is working but don't have idea how to do it for UPDATE:
$newCols = $_POST['newRowCols'];
$query = "INSERT INTO test_table VALUES "."("."NULL";
foreach($newCols as $col)
{
$query .= ",'$col'";
}
$query.=")";
mysqli_query($con,$query);
Thanks.
No this is not possible. But you can get the column names using the information_schema database:
SELECT
`ORDINAL_POSITION`,
`COLUMN_NAME`
FROM `information_schema`.COLUMNS
WHERE
`TABLE_SCHEMA` = $dbname
AND
`TABLE_NAME` = $tablename
ORDER BY `ORDINAL_POSITION`
Related
This question already has answers here:
Find out if REPLACE statement has replaced or just inserted in MySQL
(3 answers)
Closed 4 years ago.
if I have a query with field 1 being a primary key:
$rep = "Replace into table (field1,field2) values ('value1','value2')";
$stmt = $db->query($rep);
Is there a way to tell if mysql inserted the row, or found and replaced the row?
For Posterity:
$rowCount = $stmt->rowCount();
if $rowCount == 1 it was an insert, if $rowCount == 2, it was a replace.
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
To achieve this type of task mysql provide us DUPLICATE KEY UPDATE.
Below is the example how you will create new record if record is not exists in database otherwise it will update record
$rep = "INSERT into table (primaryField,field2) values ('value1','value2') ON DUPLICATE KEY UPDATE primaryField=VALUES(primaryField)";
$stmt = $db->query($rep);
For more detail you can read this
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
I think this will help you.
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
Why this line doesn't work:
$db_Table = "myTable";
$pdo->prepare("INSERT INTO :db_Table VALUES (...
$query->execute(array(
':db_Table' => $db_Table,
Whereas this one works:
$pdo->prepare("INSERT INTO myTable VALUES (...
How can I solve it ?
Tablenames can not be replaced in a PDO Query.
Further information you can find in the following thread
Can PHP PDO Statements accept the table or column name as parameter?
unfortunately there are no builtin function for binding table names, you have to do it yourself:
$db_Table = "myTable";
$query = $pdo->prepare("INSERT INTO `$db_Table` VALUES (...)");
$query->execute();
But that is still not being escaped, one workaround is to have an array of table, then check if it exist:
$list_of_tables = array('myTable1', 'myTable2', 'myTable3');
if(!in_array($db_Table, $list_of_tables){
//table does not exist !
}
This question already has answers here:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).
This question already has answers here:
Update the first row mysql php
(3 answers)
Closed 9 years ago.
I have a query that should insert data into the first row of data in the database but for some reason it does nothing. The only reason why I can think it doesn't work is because there is nothing in the table. Even so I declare what should happen if NULL.
Here is my code:
foreach ($player_fromsite as $match_player_in_game) {
$querytwo = 'UPDATE `'.$tablename.'` SET `'.$match_player_in_game.'`="'.'yes'.'" WHERE `'.$match_player_in_game.'` IS NULL ORDER BY `'.$match_player_in_game.'` ASC LIMIT 1';
for ($a = 0; $a < 11; $a++) {
if ($match_player_in_game == $home_players[$a]) {
// Insert a row of information into the table "example"
mysql_query($querytwo) or die(mysql_error());
} else {
}
}
}
The UPDATE clause will update any matching records. If there are no records you need to INSERT:
INSERT INTO `table` (aField,otherField) VALUES ("Foo","Bar");
Or to insert more than one record you can use the batch form:
INSERT INTO `table` (aField,otherField) VALUES ("Foo","Bar"),("Second Foo","Second Bar");
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”
Hello peoples
$sql1="SELECT * FROM `table` WHERE `user` = '$user'";
$res1=mysql_query($sql1);
if(!$res1||mysql_num_rows($res1)<1){
$sql2="INSERT INTO `table` (`user`) VALUES ('$user')";
$res2=mysql_query($sql2);
if(!$res2){echo 'Yes';}else{echo 'No';}
}
else{echo 'user already exists!';}
Can to combine the two queries into one?
If you set your column user to UNIQUE, there'll be a maximum of ONE entry of each user. To ALTER TABLE and make the column UNIQUE:
ALTER TABLE `table`
ADD UNIQUE INDEX `user` (`user`);
And then, a single query like this would be good:
$res = mysql_query("INSERT IGNORE INTO `table`(`user`) VALUES( '".mysql_real_escape_string($user) . "')";
echo ( mysql_affected_rows() == 0 ) ? "No" : "Yes";
mysql_affected_rows().
Use this query .
INSERT INTO USER SELECT * FROM TABLE WHERE user='$user'
the number of column in table table and user table must be same ,their type also.
you can also use
INSERT into user
SELECT * from table
WHERE user='$user'
AND
NOT EXISTS (SELECT * FROM USER
WHERE USER = '$user')