How to see if mysql replace or insert my query [duplicate] - php

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.

Related

SQL- insert and update in the same method [duplicate]

This question already has answers here:
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
(7 answers)
Postgres on conflict do update on composite primary keys
(2 answers)
Closed 6 months ago.
I have a problem with my SQL statement written in PHP.
I am using store() function to both INSERT or UPDATE object in the database following it's rule that it can be done:
The INSERT OR UPDATE command is an extension of the INSERT command, with these differences:
If the row being inserted does not exist, INSERT OR UPDATE performs an
INSERT operation. If the row being inserted already exists, INSERT OR
UPDATE performs an UPDATE operation, updating the row with the
specified column values.
I wrote type declaration for the Content ID like : public ?$contentId = null; so I can use the same methods for both actions.
public function store(Content $content, int $teamId)
{
$rsm = new ResultSetMapping($this->entityServiceRepository);
$stmt = $this->entityServiceRepository->getConnection()->prepare(
'UPDATE content
SET
name = :name,
url = :url,
WHERE id = :contentId
AND team_id = :teamId
',
$rsm
);
$stmt->bindValue("contentId", $content->getId(), PDO::PARAM_INT);
$stmt->bindValue("teamId", $content, PDO::PARAM_INT);
$stmt->bindValue("name", $content->getName(), PDO::PARAM_STR);
$stmt->bindValue("url", $content->getUrl(), PDO::PARAM_STR);
$stmt->executeQuery();
However from some reason data does not exist in the database. All bindValue() return true ant other sql queries seems to work well. How can I debug this query? Or can someone tell is there a problem with sql query I wrote.
Thanks.

How to insert multiple values in a specific field in a table using mysqli? [duplicate]

This question already has answers here:
Is storing a delimited list in a database column really that bad?
(10 answers)
Closed 7 years ago.
I am working on a project and I I have a scenario like this:
I have many field in my table :
table_name : transaction_tbl
-id
-name
-description
-ref_number : text(datatype)
In my inserting here is my code:
$sql = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`) VALUES ('$name','$desccription',$ref_number)";
if ($conn->query($sql) === false){
trigger_error('Wrong SQL: ' . $sql . 'Error: ' . $conn->error , E_USER_ERROR);
}else {
echo "Successful ! Data is inserted in database ^__^" ;
}
As the name itself ref_number or reference number, so there will be a time that I will have a lot of reference number,how can I let it insert if it will have multiple values?
Thanks :)
UPDATE :
I want something like this :
name description ref_number
bag to be use 10359435846
05438547656
035848576
Its not a good practice to have multiple values in one cell (and you should never unless there is a serious reason). It violates basic db rules. Just split this to two tables and assign foreign keys to link them up.
Learn db normalization. There are lot of examples. In here you need to take your un-normalized (0NF) table to at least to 1st normalized level (1NF). But its advised to make it normalized at least up to 3rd level
google for db normalization tutorials. As you request below image will give you an idea(field names are not same as in your question).
First insert the values to table1(Member table) and get the insert id in php use $iid = mysqli_insert_id()
Next add the multiple values as seperate rows into the second table(database table) along with the primary key obtained in first step.
Keep in mind this is not a tutorial site. find more info on net.
for what purpose ? why don't you just insert a new row with the same name and description with different ref_number ?
but if you would like that , you can concatenate your new ref_number with the existing ..
first check if it already exist
get its value then concatenate the new ref number ..
or if it doesn't exist , insert a new row ..
$sql = "SELECT `ref_number` FROM `transaction_tbl`
WHERE `name`='$name' AND `description`='$description'";
$query = mysql_query($sql);
if(mysql_num_rows($query) > 0)
{
$row = mysql_fetch_array($query);
$new_ref = $row['ref_number'] . '|' . $ref_number;
$upd = "UPDATE `transaction_tbl` SET `ref_number`='$new_ref'
WHERE `name`='$name' AND `description`='$description'";
}
else
{
$ins = "INSERT INTO transaction_tbl (`name`,`description`,`ref_number`)
VALUES ('$name','$desccription',$ref_number)";
mysql_query($ins);
}

How can I change this code to INSERT instead of UPDATE if content doesn't exist? [duplicate]

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).

How to insert data into the first row of the databse mysql php [duplicate]

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");

UPDATE table values without knowing column names PHP [duplicate]

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`

Categories