How do I insert a value to a specefic row? - php

I know how to do an insert
database::query("INSERT INTO cr VALUES ('$flname', '$email', '$pass', '$ext')");
and how to find a row
database::query("SELECT * FROM cr WHERE email='$email'")
but how do I do both, i.e. select a specefic row and then insert/update that value.

database::query("update cr set FileName='$flname', Email='$email', Pass='$pass', Ext='$ext' where email='$email');

What you want is to UPDATE an existing row. To avoid injection, you escape variables with mysql_real_escape_string and/or by preparing and binding parameters.

Inserting data into a specific row requires that this row exists; in that case you perform an UPDATE which usually has a WHERE condition just like a SELECT has.
To avoid SQL injection you want to use mysql_real_escape_string() on your variables; for numeric data it is also a good idea to cast to the desired type. Another option would be using prepared statements.

if you only want to change field in existing row:
UPDATE cr SET col = 'val' WHERE id = x
or if you wan't to insert or update:
REPLACE cr VALUES ($id, '$flname', '$email', '$pass', '$ext')
in the latter you have to put unique key on id (or other column)
there is also
INSERT INTO cr (...) ON DUPLICATE KEY UPDATE col = 'val'

Related

Mysql, How to read auto increment value in other fields of the same inserting row?

Hello I need to have the transaction id in the comment field of my transaction
mysql_query("INSERT INTO `transactiontb` (`tid`, `amount`, `comment`) VALUES (NULL,'$amount', CONCAT('Transaction # ',`tid`)')");
How can i do this?
Get off of mysql_* functions. Look at MySQLi or PDO.
Don't store the tid twice. Why not concat when you select it instead of storing it that way? This is not the best way.
For reference though, try LAST_INSERT_ID()+1):
INSERT INTO `transactiontb` (`tid`, `amount`, `comment`)
VALUES (NULL, '$amount', CONCAT_WS('Transaction # ', LAST_INSERT_ID()+1))
LAST_INSERT_ID() will give the ID of the previous INSERT not the one from the current INSERT so you must add 1.
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id
The ID that was generated is maintained in the server on a
per-connection basis. This means that the value returned by the
function to a given client is the first AUTO_INCREMENT value generated
for most recent statement affecting an AUTO_INCREMENT column by that
client. This value cannot be affected by other clients, even if they
generate AUTO_INCREMENT values of their own. This behavior ensures
that each client can retrieve its own ID without concern for the
activity of other clients, and without the need for locks or
transactions.
Use the LAST_INSERT_ID() function.
LAST_INSERT_ID() (with no argument) returns a BIGINT (64-bit) value
representing the first automatically generated value that was set for
an AUTO_INCREMENT column by the most recently executed INSERT
statement to affect such a column.
Source: MySQL Documentation
Example:
"INSERT INTO transactiontb(tid, amount, comment) VALUES (NULL,'" . $amount . "', CONCAT_WS('#','Transaction',LAST_INSERT_ID(id+1)))"
Just saw you were also forgetting to put the separator for you CONCAT_WS function, so i fixed it in the example query.

IF EXISTS MySQL

I'm from a mssql background so it's difficult to get used to MySQL.
I have a table called users_settings. Within this table there are three columns; uid, name, value. Uid is a integer and refers to the user that owns that setting, the name is the name of the setting, the value, well, you guessed it, is the value.
What I'm trying to do is update these settings if it already exists, but if it doesn't, insert a new row.
My current query is as such (Note I'm using prepared statements):
IF EXISTS (SELECT * FROM users_settings WHERE name = ? AND uid = ?) THEN
UPDATE users_settings SET value = ? WHERE name = ? AND uid = ?;
ELSE
INSERT INTO users_settings (uid, name, value) VALUES (?, ?, ?);
END IF;
The issue I'm having is that when I attempt to prepare my statement, it returns false, which therefore suggests that the syntax is incorrect. After looking in to this, it looks like it's a SQL syntax error.
Would anybody be able to point me in the relative direction as to what may be occurring here, and where I may have got my syntax incorrect?
IN MySQL, if as a statement can only used in programming blocks -- stored procedures, functions, and triggers (this is not to be confused with if as a function, which can be used in almost any SQL statement).
You can do what you want in MySQL with a single statement, insert . . . on duplicate key update. For this to work, you need a unique index on name and uid:
create unique index users_settings_name_uid on users_settings(name, uid);
And then:
INSERT INTO users_settings (uid, name, value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE value = VALUES(value);
There are two ways to fulfill your request in MySQL:
If you want to update an existing row or insert a new one if it does not exist then you should use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO users_settings (uid, `name`, `value`)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);
This relies on an unique index that contains the columns uid and name. If it does not already exist, you can create it:
ALTER TABLE users_settings
ADD UNIQUE INDEX uid_name (uid, `name`);
You need it anyway because you want a single entry in the table for each user and setting name.
If you want to insert a row in the table and replace (discard) another one that already exists then you can use REPLACE:
REPLACE INTO users_settings (uid, `name`, `value`)
VALUES (?, ?, ?);
The syntax of REPLACE is similar with the one of INSERT (but it does not support ON DUPLICATE KEY UPDATE for obvious reasons). Internally it does a DELETE followed by an INSERT (it is just a shortcut). It discards the existing row (if any) and insert the new one. It also relies on the presence of the above mentioned index (that you have no matter how you update the values in the table).
For your situation both approaches have the same outcome because there is a single column (value) that is updated or replaced. In other situations only one of them is good.
Choose the one that you feel more appropriate for your workflow and your coding style.
INSERT INTO persona_opcion(nPerCodigo,nOpcCodigo,nPerOpcEstado)
SELECT '$codPer','$idOpc',1
FROM persona_opcion
WHERE NOT EXISTS(
SELECT nPerCodigo,nOpcCodigo,nPerOpcEstado
FROM persona_opcion
WHERE nOpcCodigo='$idOpc'
and nPerCodigo='$codPer'
)
LIMIT 1;
enter link description here

Can I avoid to overwrite a column with a NULL value on INSERT query?

I have two different queries in my php page for the same table, the first one is executed if I have two different values for two columns, but in some case, i can use only the first value, can I do it with the same query or should I use two different queries?
// query 1
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";
// second query, used if $value_2 is null
"INSERT INTO my_table (column_1) VALUES ('$value_1')";
// can I do something like this without use a SELECT for column_2 before the INSERT?
$value_2 = null;
"INSERT INTO my_table (column_1, column_2) VALUES ('$value_1', '$value_2')";
// ======================================= new value === ^ | ^ === mantain old value because it's null
so can I execute an INSERT statement with new vals without overwrite the old vals with a null value?
An INSERT will never overwrite an old record (though it could fail if you try to insert a record that breaks a unique key constraint). So you can just use the first query, even if $value_2 is null, and get the same results.
If you want to overwrite records, you will need to use an UPDATE statement. In that case you could overwrite only a single column, if you wanted to. See http://dev.mysql.com/doc/refman/5.0/en/update.html for the UPDATE syntax.
There is also REPLACE to overwrite old rows in the case of unique keys, but it sounds like this is the opposite of what you want to do.

PHP MYSQL - Insert into without using column names but with autoincrement field

I need to insert a long row with 32 fields into a MySQL table.
I'd like to do something like this:
$sql="insert into tblname values (... 32 fields ...)";
Obviously, it works fine if the fields are in the same order as the MySQL table fields. But, my table has an auto-increment id as it's first field.
What I want is to fill in all table names but the first (id) one.
Suggestions?
Just use NULL as your first value, the autoincrement field will still work as expected:
INSERT INTO tblname VALUES (NULL, ... 32 Fields ... )
Insert NULL into the auto-increment field.
I recommend that unless this is a hack script, you use field names. The rationale is that your code will break if you ever add a field to the table or change their order.
Instead, be explicit with field names, and it will go much better in the future.
Use NULL or 0 to insert an auto-incremented value as shown below:
-- Here
INSERT INTO tblname VALUES (NULL, ... 32 Fields ... )
-- Here
INSERT INTO tblname VALUES (0, ... 32 Fields ... )
We should omit any column values when we try without column name in insert query,
Advise if above information is wrong.
Here's a simple shortcut that I've used:
$fieldlist=$vallist='';
foreach ($_POST as $key => $value) {
$fieldlist.=$key.',';
$vallist.='\''.urlencode($value).'\','; }
$fieldlist=substr($fieldlist, 0, -1);
$vallist=substr($vallist, 0, -1);
$sql='INSERT INTO customer_info ('.$fieldlist.') VALUES ('.$vallist.')';
Please note that this code would be vulnerable to SQL Injection and should be modified to accommodate PDO's, but I felt this simplified script would more directly answer the question with regards to the originally posted code.

Sql Query not working!

INSERT INTO `test` (`x`, `y`) WHERE `id` = `$id`
VALUES (`$x`, `$y`)
Whats wrong with this query? I run this in a mysql_query() function in a php file.
You can't use a Where clause with an insert. You are either inserting a row or you're not.
If you're trying to update information from the database, use UPDATE instead of INSERT INTO in the query you're running.
You can't use a where clause on an insert. I think you might be wanting an update statement:
update test set
x = $x,
y = $y
where id = $id
When you're inserting a new value in the database, you usually don't have an ID value until after the insert (assuming you're using auto-generated IDs).
You need to remove the "WHERE id=$id" - it has no meaning in an INSERT statement.
So, either
UPDATE test SET x='x', y='$y' WHERE id ='$id';
OR
INSERT INTO test ('x', 'y') VALUES ('$x', '$y');
as stated in other posts - you cannot do an INSERT with a WHERE.
Also note that you must use single quotes (') rather than backticks (`) for values. Backticks are used when referencing column names / field names.
This:
`field` = '$value'
rather than this:
`field` = `$value`
unless you really do want to reference another field. This is sometimes what you want when copying values or matching JOINs and such. But because you have a variable there, I'm assuming you want to use single quotes rather than backticks.

Categories