if(isset($_POST['admin_email']))
{
$conn= mysql_connect("localhost","root","","");
mysql_select_db("qasite" ,$conn) or die(mysql_error());
$email=mysql_escape_string($_POST['admin_email']);
mysql_query(" UPDATE admin_details
SET email='$email'
WHERE admin_id=1
") or trigger_error(mysql_error(),E_USER_ERROR);
echo 'Update was successful';
}
The update statment at the end appears, but no record appears in the database. By default I set the admin_id equal 1, and no update happens. Why is that?
but no record appears in the database.
You can use UPDATE only on records that exist. If there is no record WHERE admin_id = 1, the query won't update non-existing rows.
You could use INSERT and work with the ON DUPLICATE KEY UPDATE. (then email should be an UNIQUE index).
You can change trigger_error to die(mysql_error()) and see if it works better.
Related
I've just started with php, and i wondered if anyone can help.
i have this
$sql="INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
I need to know how to make it see if the event exists, and if it does i need it to do nothing, if it doesn't then insert it!
split it into 2 queries:
1) check if event exists. If yes then do nothing, else insert a new event
2) continue with your query. this way the event will allays exist when inserting your data
This is something that can be done through MySQL alone.
Setup a unique key for the event column by running the following MySQL Command on your table:
CREATE UNIQUE INDEX `i_event` ON `TABLE_NAME_GOES_HERE` (`event`);
For more information: http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Do this for every possible table you expect to see in the $tbl_name variable.
Then, change your PHP Query:
$sql="INSERT IGNORE INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result=mysql_query($sql);
For more information on INSERT IGNORE: http://dev.mysql.com/doc/refman/5.5/en/insert.html
INSERT IGNORE simply does as it states... it will try to insert the row unless it fails validation (in this case from an index that you declared HAS to be unique).
Try:
$query = mysql_query("SELECT $myevent from $tbl_name ")
$rows = mysql_num_rows($query)
if ($num_rows > 0) {
// do nothing
}
else {
$sql = "INSERT INTO $tbl_name SET date='$mydate' , event='$myevent'";
$result = mysql_query($sql);
}
As a sidenote: mysql_ functions are deprecated and it's recommended to switch to mysqli or PDO.
I have an issue where I can only insert data into my table once. If i delete the row and insert a new one, it works but if I already have a row and try to insert another one, it doesn't work. No errors in the console or network.
I'm inserting with this:
<?php
error_reporting(E_ALL);
include 'DB.php';
$con = mysql_connect($host,$user,$pass)
or die("Error: ".mysql_error());
$dbs = mysql_select_db($databaseName, $con);
$name = mysql_real_escape_string($_POST['name']);
$date = date('Y-m-d');
$amount = $_POST['amount'];
$timPaid = $_POST['timPaid'];
$rennyPaid = $_POST['rennyPaid'];
$sql = "INSERT INTO $tableName (`name`, `date`, `amount`, `timpaid`, `rennypaid`)
VALUES ('$name', '$date', '$amount', '$timPaid', '$rennyPaid')";
$result = mysql_query($sql, $con)
or die("Error: ".mysql_error());
mysql_close($con);
?>
I'm thinking it might have to do with how my table is set up, primary key and such. I have an id column which is the primary and I think it's auto-increment, can't tell.
Since you are not sure about whether the id field is auto-increment or not, you should alter your table like this,
ALTER TABLE `yourtable`
MODIFY COLUMN `id` int(11) NULL AUTO_INCREMENT FIRST;
the result FROM SHOW CREATE TABLE tableName would help.
I would guess you have a unique index on on of your fields and you are trying to insert a second record with the same value.
Also CHECK TABLE tablename could help identify the problem.
I had this... I had set my first column as 'unique' and my 'Insert' didn't involve that column.
As a result the 'Insert' added a value of zero into the 'Unique' column (I'd set that column to 'integer').
When I did another insert 'I THINK' that the 'Insert' wanted to add another zero in the 'Unique' column that I wasn't 'Inserting' into, so it tried to 'Insert' another zero, BUT because that column was 'unique' it wouldn't allow another zero and refused the 'Insert'.
I proved this by changing the first 'Inserts' entry into the 'Unique' column manually to another 'Integer' then the 'Insert; statement worked one more time.... repeat process above as described and my table allowed another 'Insert'.
Hope this makes sense and helps?.
I had a similar problem, however mine was where I was using the INT data type in my create table script for storing a 13-digit long number, and it only wanted to accept something 10-digits in size. Changing this to a VARCHAR(13) fixed the problem for me.
I'm using MySQL 5.1 hosted at my ISP. This is my query
mysql_query("
IF EXISTS(SELECT * FROM licensing_active WHERE title_1='$title_1') THEN
BEGIN
UPDATE licensing_active SET time='$time' WHERE title_1='$title_1')
END ELSE BEGIN
INSERT INTO licensing_active(title_1) VALUES('$title_1')
END
") or die(mysql_error());
The error is
... check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM licensing_active WHERE title_1='Title1') THEN ' at line 1
My actual task involves
WHERE title_1='$title_1' AND title_2='$title_2' AND version='$version' ...ETC...
but I have reduced it down to make things simpler for my problem solving
In my searches on this, I keep seeing references to 'ON DUPLICATE KEY UPDATE', but don't know what to do with that.
Here is a simple and easy solution, try it.
$result = mysql_query("SELECT * FROM licensing_active WHERE title_1 ='$title_1' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE licensing_active SET time = '$time' WHERE title_1 = '$title_1' ");
}
else
{
mysql_query("INSERT INTO licensing_active (title_1) VALUES ('$title_1') ");
}
Note: Though this question is from 2012, keep in mind that mysql_* functions are no longer available since PHP 7.
This should do the trick for you:
insert into
licensing_active (title_1, time)
VALUES('$title_1', '$time')
on duplicate key
update set time='$time'
This is assuming that title_1 is a unique column (enforced by the database) in your table.
The way that insert... on duplicate works is it tries to insert a new row first, but if the insert is rejected because a key stops it, it will allow you to update certain fields instead.
The syntax of your query is wrong. Checkout http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Use the on duplicate key syntax to achieve the result you want. See http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
Another solution
$insertQuery = "INSERT INTO licensing_active (title_1) VALUES ('$title_1')";
if(!$link->query($insertQuery)){ // Insert fails, so update
$updateQuery = "UPDATE licensing_active SET time='$time' WHERE title_1='$title_1'";
$link->query($updateQuery);
}
Here is the example I tried and its works fine:
INSERT INTO user(id, name, address) VALUES(2, "Fadl", "essttt") ON DUPLICATE KEY UPDATE name = "kahn ajab", address = "Address is test"
I am amazed to see so many useless codes and answers...
Just replace INSERT with REPLACE.
¯\(ツ)/¯
I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.
Im trying to write a function to check whether a user exists in a table, if so, update the row, if not, insert it.
Here is my function:
function UserExists($screenname){
$mysql = mysql_fetch_array ( mysql_query("SELECT * FROM `users` WHERE `screenname` = '$screenname' "));
if($mysql){
return TRUE;
}else{
return FALSE;
}
}
And im executing this function using the following:
if(UserExists($user)){
mysql_query("UPDATE `users` SET `token` = '$token' , `secret` = '$secret' WHERE `screenname` = '$user' ");
}else{
mysql_query("INSERT INTO `users` (`screenname`, `token`, `secret`) VALUES ('$user', '$token', '$secret')");
}
Its not doing anything, not throwing any errors, but also not updating the table.
You'd want to take a look at the INSERT ... ON DUPLICATE KEY UPDATE ... MySQL query syntax to make this work with just one query.
INSERT INTO users (screenname, token, secret) VALUES ('screenname', 'token', 'secret')
ON DUPLICATE KEY UPDATE token = 'token', secret = 'secret'
screenname should be unique (or a primary key) which you probably don't have at the moment. I suggest to add an ID column in your database table and use that to refer to database rows.
Your best solution is ON DUPLICATE KEY as JoostK stated
Call mysql_error after the calls to see what error you are getting. Also another good debugging technique is to execute it on the server using a MySQL client such as mysqlfront or phpMyAdmin.
I'd simply suggest to use REPLACE INTO SET col = val in this case, all you need to do is define a unique index on the table.
The Replace Command will have a look at the unique indexes, if a row already exists it will update the existing, if not it will insert a new one.