By according to this question I have 2 table Source and details .
The Source table is as follows:
+----+----------+---------------+-----------+
| id | item_name|items_download | category |
+----+----------+---------------+-----------+
| |
+----+----------+---------------+-----------+
The details table is as follows:
+------+----------+-----+------+
| name | download | time| ip |
+------+----------+-----+------+
| |
+------+----------+-----+------+
At first step I want to get data from Source table (in real time) and put into details table by this code:
$get= "INSERT INTO `details` (`name`, `download`) SELECT `Source`.`item_name`,`Source`.`items_download` FROM `Source`"
At next step I want to get visitor IP address for each file.
for example if someone downloaded testfile I want to have this output:
+----------+---------+--------------+-----------+
| name | download | time | ip |
+----------+----------+-------------+-----------+
| testfile | 32 |download time|192.168.0.0|
+----------+----------+-------------+-----------+
| file2 | 0 | | |
+----------+----------+-------------+-----------+
To do this i use this code:
$ip = $_SERVER['REMOTE_ADDR'];
$update = "UPDATE details SET ip = '$ip', dldate = NOW()"
But its happened for all files, all of the file get same IP and time. I know its need a condition WHERE but I don't know what should I type as a condition to get IP address for each file that download.
Imho you don't need any UPDATE query. You just do an INSERT everytime a user requests a file:
<?php
$fileid = $_GET['fileid'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$sql = "SELECT * FROM Source WHERE id=" . (int)$fileid;
foreach ($pdo->query($sql) as $row) {
$statement = $pdo->prepare("INSERT INTO details (name, download, time, ip) VALUES (?, ?, NOW(), ?)");
$statement->execute(array(
$row['item_name'],
$row['items_download'],
$_SERVER['REMOTE_ADDR'],
));
}
?>
Some hints on the code above:
Use prepared statements - never inject any value directly into an SQL string.
It might be useless to insert file_name and items_download into the details table everytime. You have this information in your table "Source" anyway. So usually you would just put Source.id into your details table.
You should use your id column, which you have in your first table view, but it stragely disappears in the later ones.
Your id column should also be your PRIMARY_KEY AUTO INCREMENT column. Then each row has its own unique and indexed id.
But aside from that, what do you use to identify which file the user downloads? If it's the filename then simply use that:
EDIT: Add an id column to your details table!
$update = "UPDATE details SET ip = '$ip', dldate = NOW()
WHERE name = '$fileNameValue' LIMIT 1"
On a related note, you can not update multiple columns with the same shorthand reference of device = ip = '$ip' you have to specify each column in isolation and with an absolute target data to insert (here, the variable) .
If this is a typo you should edit and update your question.
Please also see Gerfried's answer regarding using prepared statements, they are the way you should be doing these things.
I think you need to get the session of user when he downloads the file and add it to the WHERE condition.
Related
I have a database with following table test_users:
| id | Username | Password |
| 1 | pat | ***** |
| 2 | roger | ***** |
| 3 | luke93 | ***** |
And to insert a new row I use following code, and it works fine:
$sql = $conn->prepare("INSERT INTO `test_users` (`Username`, `Password`) VALUES (?,?)");
$sql->bind_param('ss',$name, $email);
But now i am trying to make a "update profile"-page and I wanted to use ON DUPLICATE KEY. That means I need to check if idexists and if so update the row. Neither Username or Password is Unique, but id is. I have a $_SESSION["id"] which is available if the user is logged in. Can I use that in some way?
So how do I write a SQL-sentence that finds out if id exist, and if so, overwrite it with ON DUPLICATE KEY (or a better way)?
first write selct query and count num rows if its 0 then insert query fire else update query
UPDATE works the same as an insert. You just need to pass the WHERE condition.
You can do this with the following code, Try it
$id = $_SESSION['id'];
$sql = "UPDATE test_users SET Username=?, Password=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param($Username, $Password, $id);
$stmt->execute();
Assign unique key of your unique field and try below query
Insert into a MySQL table or update if exists
INSERT INTO test_user(id, username, password) VALUES(1, "test", "test") ON DUPLICATE KEY UPDATE
username="test", password="test"
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
credits to Donnie
I have a program that can perform inserts and updates to the database, I get the data from API.
This is sample data when I get:
$uname = $get['userName'];
$oname = $get['offerName'];
$visitdata= $get['visits'];
$convdata = $get['conversion'];
I save this data to database sql. (sucess) this is a sample:
$sql = "INSERT INTO data_tester(username_data, name_offer_data, visit_data, conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')";
Sample data in database table
id | username_data | name_offer_data | visit_data | conversion_data
1 | MOJOJO | XXX AU | 177 | 13
2 | MOJOJO | XX US | 23 | 4
Now, I want to save data $uname, $oname, $visitdata, $convdata if NOT EXIST and UPDATE $visitdata, $convdata where $uname, $oname if EXIST
How to run the code with a simple query.
Please give me an example.
Thank you.
The feature you are looking for is called UPSERT and it is the part of SQL-2008 Standard. However not all DBMS-s implement it and some implement it differently.
For instance on MySQL you can use:
INSERT ... ON DUPLICATE KEY UPDATE
syntax (link to docs)
or
REPLACE INTO
syntax (link to docs).
These methods require you to have a proper PRIMARY KEY: (username_data name_offer_data) in your case.
Some PHP frameworks support this feature too provided you are using ActiveRecord (or similar) class. In Laravel it is called updateOrCreate and in Yii it is called save(). So if you are using a framework try to check its documentation.
If you are using neither framework nor modern DBMS you have to implement the method yourself. Run SELECT count(*) from data_tester WHERE username_data = ? AND name_offer_data = ?, check if it returned any rows and call an appropriate UPDATE/INSERT sql
it's simple, try this:
if(isset($get['userName'])){
$sql = "SELECT * FROM data_transfer WHERE userName = ".$userName.";";
$result = connection()->query($sql);
$rs = mysqli_fetch_array($result);
connection()->close();
//if is not void, means that this username exists
if ($rs != ''){
mysqli_free_result($result);
//InsertData
}
else{
mysqli_free_result($result);
//UpdateData
}
*chech that you have to use your PrimaryKey on where clause to ensure there are only one of this. if you use an ID and you don't get it by $_GET, you'll have to modify something to ensure non-duplicated data. For example, checking that userName cannot be duplicated or something similar
You can simply use replace into command instead of insert into command.
$sql = "REPLACE INTO data_tester(username_data, name_offer_data, visit_data, conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')";
It is one of mysql good and useful feature. I used it many times.
Please ensure there is a unique key on column username_data, if so Mysql's ON DUPLICATE KEY UPDATE is suitable for this case, the SQL statement is like that:
$sql = "INSERT INTO data_tester(username_data, name_offer_data, visit_data,
conversion_data) VALUES('$uname','$oname', '$visitdata', '$convdata')
ON DUPLICATE KEY UPDATE username_data = '$uname', name_offer_data =
'$oname', visit_data = '$visitdata', conversion_data = '$convdata'"
In database I already have this inside:
id | username | password
=========================
3 | John | happy
The same user register an account whose id of 3 is stored in PHP session. I want to store another row where the id is also 3 into the database.
The output will be something like this:
id | username | password
=========================
3 | John | happy
3 | Emily | sad
So far I got this:
abc.php
$result = mysql_query("SELECT id FROM account WHERE username='".$username."' LIMIT 1") or die(mysql_error);
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['id'] = $row['id'] ;
}
<input type="hidden" name="custom" value="<?php echo $_SESSION['id'];?>">
cba.php
$id = $_POST['custom'];
mysql_query("INSERT INTO user (id, username, password) VALUES('".$id."', '".$username."', '".$password."')") or die(mysql_error());
I tried with the session where the id is 3 and try to insert into the database but nothing is inserted.
Very curious why you want to do this. Any who, you could try something like:
$sql = "INSERT INTO user (id, username, password)
SELECT MAX(id), '" . $username . "', '" . $password . "' FROM user";
Hope you're also not storing the password in plain text.
What you are trying to do is have "two unique" values that are the same. It can't be done. Else the values aren't unique anymore.
To answer you question, if the field you want to store the value in is not a field where you enforce uniqueness, then a simple insert should do it. Unless you want to fetch values from the database and make duplicates. It's hard to make out what you want. But just trying to insert a value you know is already in the field. It will work if it's not a unique or a primary field.
I think you need an update query. As the id is already present(user is registered as he session has an id), you need to update the existing user's info with new details.
I have a database name q8marketz there is a table product inside. This table has many fields eg:- product id, model, quantity, shipping, etc...
I have uploaded many products to my table... there is a field shipping, the shipping value is already set to 1for all products, so now I want to set all product shipping values to 0.
anybody can help me?
Sorry my English is not perfect...
Two product details given below...
===Database q8marketz
== Table structure for table product
|------
|Field|Type|Null|Default
|------
|//**product_id**//|int(11)|No|
|model|varchar(64)|No|
|downpayment|varchar(32)|No|
|sku|varchar(64)|No|
|upc|varchar(12)|No|
|ean|varchar(14)|No|
|jan|varchar(13)|No|
|isbn|varchar(13)|No|
|mpn|varchar(64)|No|
|location|varchar(128)|No|
|quantity|int(4)|No|0
|stock_status_id|int(11)|No|
|image|varchar(255)|Yes|NULL
|manufacturer_id|int(11)|No|
|shipping|tinyint(1)|No|1
|price|decimal(15,4)|No|0.0000
|points|int(8)|No|0
|tax_class_id|int(11)|No|
|date_available|date|No|
|weight|decimal(15,8)|No|0.00000000
|weight_class_id|int(11)|No|0
|length|decimal(15,8)|No|0.00000000
|width|decimal(15,8)|No|0.00000000
|height|decimal(15,8)|No|0.00000000
|length_class_id|int(11)|No|0
|subtract|tinyint(1)|No|1
|minimum|int(11)|No|1
|sort_order|int(11)|No|0
|status|tinyint(1)|No|0
|date_added|datetime|No|0000-00-00 00:00:00
|date_modified|datetime|No|0000-00-00 00:00:00
|viewed|int(5)|No|0
== Dumping data for table product
|886|BA-HANDBAGS-001ss| | | | | | | |aaaa|95|7|data/hand-bags.jpg|7|1|32.5000|25|0|2012-09-03|0.00000000|1|0.00000000|0.00000000|0.00000000|1|1|1|1|1|2012-09-25 13:00:18|0000-00-00 00:00:00|0
|883|BA-HANDBAGS-001ss| | | | | | | |aaaa|95|7|data/hand-bags.jpg|7|1|32.5000|25|0|2012-09-03|0.00000000|1|0.00000000|0.00000000|0.00000000|1|1|1|1|1|2012-09-17 14:08:08|2012-09-25 13:00:06|9
== Table structure for table product
|------
|Field|Type|Null|Default
|------
|//**product_id**//|int(11)|No|
|model|varchar(64)|No|
|downpayment|varchar(32)|No|
|sku|varchar(64)|No|
|upc|varchar(12)|No|
|ean|varchar(14)|No|
|jan|varchar(13)|No|
|isbn|varchar(13)|No|
|mpn|varchar(64)|No|
|location|varchar(128)|No|
|quantity|int(4)|No|0
|stock_status_id|int(11)|No|
|image|varchar(255)|Yes|NULL
|manufacturer_id|int(11)|No|
|shipping|tinyint(1)|No|1
|price|decimal(15,4)|No|0.0000
|points|int(8)|No|0
|tax_class_id|int(11)|No|
|date_available|date|No|
|weight|decimal(15,8)|No|0.00000000
|weight_class_id|int(11)|No|0
|length|decimal(15,8)|No|0.00000000
|width|decimal(15,8)|No|0.00000000
|height|decimal(15,8)|No|0.00000000
|length_class_id|int(11)|No|0
|subtract|tinyint(1)|No|1
|minimum|int(11)|No|1
|sort_order|int(11)|No|0
|status|tinyint(1)|No|0
|date_added|datetime|No|0000-00-00 00:00:00
|date_modified|datetime|No|0000-00-00 00:00:00
|viewed|int(5)|No|0
You can easily use an update query like this:
update product set shipping=0;
This will update all the rows to 0.
If you want to only specify certain selected rows, you can add a where clause to limit the number of rows that you update like this:
update product set shipping=0 where points>2;
This would update all the rows where points has a value greater than 2.
Edit: The code can be run directly from the mysql console, or via a database call from within PHP like this:
$dbh = new PDO($hostname, $username, $password);
$sql='update product set shipping=0 where points>2';
$stmt = $dbh->query($sql);
You can use the SQL UPDATE statement to update existing records in your table.
SQL UPDATE Syntax :
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
For your examlpe use :
UPDATE product
SET shipping=0;
==>The code can be run directly from the mysql console.
To use PHP Call try the code:
<?php
$dataBase = new PDO($hostname, $username, $password);
$sqlQuery ='update product set shipping=0';
$stmt = $dataBase->query($sqlQuery );
?>
my table(s) structure (MySQL / each one is same as below)
+-------+--------------+------+------+-------------------+
| Field | Type | Null | Key | Default |
+-------+--------------+------+------+-------------------+
| id | int(11) | NO | PRI | AUTO INCREMENT |
| lesson| varchar(255) | NO | | LESSON_NAME |
| exam | char(50) | NO |UNIQUE| NO DEFAULT |
| quest | text | NO | | NO DEFAULT |
| answer| text | NO | | NO DEFAULT |
| note | text | NO | | NO DEFAULT |
+-------+--------------+------+------+-------------------+
and i'am posting some values to add this table via ajax ($post) - PHP 5.0
in database.php there is a function to get posted data and add to table
function update_table ($proper_table, $name, $question, $answer, $note) {
$sql = "INSERT INTO $proper_table (id, lesson, exam, quest, answer, note) VALUES ('', '', $name, $question,$answer,$note) ON DUPLICATE KEY UPDATE exam = $name, quest = $question, answer = $answer, note = $note";
$result= mysql_query($sql)or die(mysql_error());
}
$proper_table variable is taken by another variable to add this record to correct table.
(NOTE: Original table fields and variables are different (Turkish), to be more understandable i traslated to english but the syntax is the same as you see.)
Question : I want to check that if there is a record that exam field is same then all these variables will be used for updating this record, otherwise let function put this record to proper table as a new record.
But i'am getting error like below
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
is there any faulty coding? and what can be the solution?
Thanks right now...
function update_table ($proper_table, $name, $question, $answer, $note) {
$sql = "INSERT INTO $proper_table (lesson, exam, quest, answer, note) VALUES ('', '$name', '$question','$answer','$note') ON DUPLICATE KEY UPDATE quest = VALUES(quest), answer = VALUES(answer), note = VALUES(note)";
$result= mysql_query($sql)or die(mysql_error());
}
Just breaking this out I'll detail the changes
$sql = "INSERT INTO $proper_table
// Removed the PK (primary key) AI (auto increment) field - don't need to specify this
(lesson, exam, quest, answer, note)
// Likewise removed PK field, and added quotes around the text fields
VALUES ('', '$name', '$question','$answer','$note')
ON DUPLICATE KEY UPDATE
// If you specify VALUES(fieldName) it will update with the value you specified for the field in the conflicting row
// Also removed the exam update, as exam is the UNIQUE key which could cause conflicts so updating that would have no effect
quest = VALUES(quest), answer = VALUES(answer), note = VALUES(note)";
You need to wrap you string variables in single quotes in your SQL '$name' for example. Otherwise mysql thinks you are referencing column names.
With that query, when you add ON DUPLICATE KEY UPDATE... it will update when the id es the same than the id that you are sending, in this case you are not sending an id as parameter so it will never update because you have the id with auto-increment.
A solution could be that you read the table where exam equals the parameter you are sending, something like this:
SELECT id FROM $proper_table;
If it is null the you execute an insert, if it is not null the you update taking as parameter the id that you are getting from the select
id auto-increments, so presumably you don't want to set an empty string as id.
Try:
$sql = "INSERT INTO $proper_table (lesson, exam, quest, answer, note) VALUES ('', $name, $question,$answer,$note) ON DUPLICATE KEY UPDATE exam = $name, quest = $question, answer = $answer, note = $note";
You have to make it like this
<?php
function update_table($proper_table, $name, $question, $answer, $note, $id) {
$sqlQuery = "INSERT INTO '".$proper_table."' SET
name = '".$name."',
question = '".$question."',
answer = '".$answer."',
note = '".$note."' WHERE id = '".$id."'";
$result= mysql_query($sqlQuery)or die(mysql_error());
}
?>