I am inserting records in user_table with user_email as primary key.
$result = mysqli_query($db, "insert into user_table(user_full_name, user_email, user_password) values('".$fullnames."','".$emails."','".$passs."')");
How to know that insert failed due to duplicate primary key, without quering once again to user_table
mysqli_errno(), function can help you,
try this
if (!$result )
{
if(mysqli_errno($con) == 1062){
echo "duplicate entry";
}else{
echo("Error description: " . mysqli_error($con));
}
}
For More error code :https://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html
I can answer my question myself.
after query
I can check
if( mysqli_errno($db) == 1062 ) {
""*DUPLICATE PRIMARY KEY**
}
Related
i made module for prestashop. Just basic administration form with write into DB. But when i try to install module at Prestashop, i have this error:
[PrestaShopDatabaseException]
Duplicate entry '0' for key 'PRIMARY'
INSERT INTO `ps_module` (`name`, `active`, `version`) VALUES ('apishippingtextsource', '1', '0.0.1')
at line 635 in file classes/db/Db.php
629. WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.$this->getMsgError().'. From '.(isset($dbg[3]['class']) ? $dbg[3]['class'] : '').'->'.$dbg[3]['function'].'() Query was : '.$sql, 97);
630. }
631. else if (_PS_DEBUG_SQL_ && $errno && !defined('PS_INSTALLATION_IN_PROGRESS'))
632. {
633. if ($sql)
634. throw new PrestaShopDatabaseException($this->getMsgError().'<br /><br /><pre>'.$sql.'</pre>');
635. throw new PrestaShopDatabaseException($this->getMsgError());
636. }
637. }
638.
639. /**
my install.php for sql:
$sql = array();
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'api_shipping_text` (
`id_text` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id_text`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
Version of Prestashop is 1.6.0.9.
Can you check the auto_increment value of your ps_module table structure? Maybe auto_increment is not defined or set to 0.
If that's the case, you probably had an error during Database migration or installed another module messing with auto_increment.
I have a table structure with META_ID | KEY | VALUE | USER_ID where META_ID is auto-increment. Now in my php logic
1 get the result key-value pairs per user
2 delete the key value row per user
3 update or insert the key value pair for a already known USER_ID
4 insert key value pair for a new user
But the META_ID keeps growing, so i was wondering if i could just delete the META_ID column?
Case logic
An registered user or returning registered user can update their form over time if they haven't submit it yet. So overtime an user can select and deselect certain form options and update, insert or delete is triggered.
Now the logic behind "returning user deselects a key (and the row needs to be deleted)" gives me a problem. That's why i just delete all users key-value pairs. But what would be the right way?
So if the key-value exists in the db table but not in $params i need to delete it!
btw here's my function
function user_shopping_meta_data($params) {
global $wpdb;
$shopping_meta_table = 'wp_shopping_metavalues';
$wp_user_id = $params['wp_user_id'];
//1 CHECK IF USER HAS KEY VALUE PAIRS
$checkKeyValues = $wpdb->get_results("SELECT meta_shopping_key FROM $shopping_meta_table WHERE wp_user_id = '$wp_user_id'");
//2 WE DELETE
$qdel = $wpdb->delete($shopping_meta_table, array('wp_user_id' => $wp_user_id));
//3 UPDATE OR INSERT
foreach ($params as $key => $val) {
//variables
if (is_array($val)) {
$val = json_encode($val);
}
$shopping_meta_values = array(
'wp_user_id' => $wp_user_id,
'meta_shopping_key' => $key,
'meta_shopping_value' => $val
);
if (count($checkKeyValues) > 0) {//3 USER IS KNOWN SO UPDATE and/or INSERT new key-value
foreach ($checkKeyValues as $check) {
//UPDATE OR INSERT
if (($key != "wp_user_id")) {
//FOR UPDATE where
$shopping_meta_where = array('meta_shopping_key' => $key, 'wp_user_id' => $wp_user_id);
$result = $wpdb->get_results("SELECT * FROM $shopping_meta_table WHERE meta_shopping_key = '" . $key . "' AND wp_user_id = '$wp_user_id'");
if (count($result) > 0) {//KEY ALREADY EXISTS FOR USER
$return .= $wpdb->update($shopping_meta_table, array('meta_shopping_key' => $key, 'meta_shopping_value' => $val), $shopping_meta_where) . '<br/>';
//$return .= 'UDPATE<br/>';
} else {//KEY IS NEW
$return .= $wpdb->insert($shopping_meta_table, $shopping_meta_values) . '<br/>';
// $return .= 'INSERT for old';
}
}//.end $key
}//.end foreach checkKeyValue
}//.end count
else {//4 INSERT KEY VALUE PAIR FOR NEW USER
if (($key != "wp_user_id")) {
$return .= $wpdb->insert($shopping_meta_table, $shopping_meta_values) . '<br/>';
// $return .= 'INSERT NEW';
}
}
}//.end each
echo 'Test return: ' . $return;
}
You won't gain much by deleting it. You might think that you save some space, but in fact you don't. An auto_increment column is always also (part of) the primary key. If you delete it, MySQL will create an "implicit" primary key, which is not visible but necessary for MySQL to identify rows. Also you will lose some comfort like not being able to use LAST_INSERT_ID().
You can very well delete it. It is just a unique ID. If you can distinguish different rows without the META_ID or you do not need to distinguish rows, then META_ID is redundant.
If i can give you a suggest is better to leave that field as a history.
If you need to want to know what is the last action done for that user you can order by META_ID.
Is usefull to have a primary key in a table. But this is just a suggest
I suggest you have a primary key that you are sure of that it is unique. It is a good idea to use a auto-increment column for this because you will always be sure that it is unique.
I can't resolve my problem, this is the error from mysql that I'm getting:
I can edit and update my data when I've got one record in the database but when I add two rows, I get the error.
Some pictures from database
And when I change the row, row ID goes down to 0 and that's is a problem as I can't edit other rows.
CREATE TABLE `dati` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`value1` varchar(255) NOT NULL,
`value2` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 PACK_KEYS=1
Update Code:
<?php // Izlabot datus datubāzē!
$titletxt = $_POST['title_edit'];
$value1 = $_POST['value1_edit'];
$value2 = $_POST['value2_edit'];
if(isset($_POST['edit'])){
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$sql="UPDATE dati SET ID='$ID',title= '$titletxt',value1='$value1',value2='$value2' WHERE 1";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo '<script>
alert(" Ieraksts ir veiksmīgi labots! ");
window.location.href = "index.php";
</script>';
mysqli_close($con);
}
?>
From form:
<?php
$con=mysqli_connect("localhost","root","","dbname");
if (mysqli_connect_errno())
{
echo "Neizdevās savienoties ar MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM dati");
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td><input id='titled' type='text' name='title_edit' value='" . $row['title'] . "'></td>";
echo "<td><input id='value1d' type='text' name='value1_edit' value='" . $row['value1'] . "'></td>";
echo "<td><input id='value2d' type='text' name='value2_edit' value='" . $row['value2'] . "'></td>";
echo "<input type='hidden' name='id' value='" . $row['ID'] . "'>";
echo "<td><button name='edit' id='edit_btn' class='frm_btns' value='" . $row['ID'] . "'>Edit</button></td>";
echo "</tr>";
}
mysqli_close($con);
?>
It couldn't read the value of ID, as 0 was returned.
For those arriving at this question because of the question title (as I did), this solved my problem:
This error can indicate that the table's PRIMARY KEY is not set to AUTO-INCREMENT, (and your insert query did not specify an ID value).
To resolve:
Check that there is a PRIMARY KEY set on your table, and that the PRIMARY KEY is set to AUTO-INCREMENT.
How to add auto-increment to column in mysql database using phpmyadmin?
The error log like (In my case), I'm using Aurora DB:
PHP message: WordPress database error Duplicate entry '0' for key 'PRIMARY' for query INSERT INTO `date173_postmeta
How to fix it using MySQL Workbench:
1- Connect at your DB, and go to the table with the issue, in my case date173_postmeta
2- Select the tools icon:
3- In the windows/tab at right, select the AI checkbox and click on Apply button:
Following the last steps my issues gone.
The problem is that your code attempts to change every row in the data changing the primary key to the value in $ID. This is not set anywhere in your code, and presumably is being cast as 0
$sql="UPDATE `dati` SET `ID`='$ID',`title`=
'$titletxt',`value1`='$value1',`value2`='$value2' WHERE 1";
The primary key value should be sent to the form and returned so it can be processed by your code, but the value should be retained, hence....
$sql="UPDATE `dati` SET `title`=
'$titletxt',`value1`='$value1',`value2`='$value2' WHERE `ID`=$ID";
You should also read up on MySQL injection - even after you've fixed the errors here, anyone can do just about anything they want with your database.
Try this:
ID int(11) PRIMARY KEY AUTOINCREMENT(1,3)
The problem in set ID = $ID
Try removing it so the code should be
$sql="UPDATE `dati` `title`= '$titletxt',`value1`='$value1',`value2`='$value2' WHERE 1";
Be sure to change this where cause it'll update ever row with these values
Just make sure that your primery keys are also A-I.
I'd been struggling to fix this. My tables had auto increment (AI) switched on
Before I started tinkering with records I tried a simple repair in phpMyAdmin.
Go to the SQL tab and run each command in turn.
REPAIR TABLE wp_options
REPAIR TABLE wp_users
REPAIR TABLE wp_usermeta
This did the trick for me and allowed me to login.
i am using phpmyadmin,
so go to db , search for wp_postmeta tabel
add AI(auto-increment) to meta_id
save the changes
I have a table that maps itemId(item.id) and tagId(tag.id).
I'm writing a query that needs to insert a new row, but only if BOTH itemId and tagId do not already have an entry. What's the best way to do this?
Here is my current query that doesn't already check for an existing match:
// create tag-item maps
$sql = 'INSERT INTO item_tag
SELECT :itemId AS iid, tag.id AS tid
FROM tag
WHERE tag.name=:name';
try{
$stmt = $db->dbh->prepare($sql);
for($i = 0; $i < $count; $i++) {
$data = array(':itemId' => $itemId, ':name' => $tags[$i]);
$result = $stmt->execute($data);
if($result !== false) {
// Do nothing
}else {
return false;
}
}
return true;
}catch(PDOException $e) {
logit($e->getMessage());
return false;
}
A UNIQUE constraint would be the ideal solution, and according to the docs the MyISAM engine supports them.
ALTER TABLE item_tag ADD CONSTRAINT item_tag_iid_tid_uq UNIQUE (iid, tid);
Then if your INSERT tries to add a duplicate (iid, tid) pair it will throw and you can handle it in your catch code.
If you don't want to do the UNIQUE constraint, you could instead add an "existence" check to your INSERT query:
INSERT INTO item_tag
SELECT :itemId AS iid, tag.id AS tid
FROM tag
WHERE tag.name=:name' AND NOT EXISTS (
SELECT * FROM item_tag WHERE iid=:itemId AND tid=tag.id)
I tested this using my own differently-named tables, so hopefully I "translated" it correctly to your table/column names.
how do i check if the value of a column is null, and only then execute the query? for example:
col1 col2 col3
01 abc
i run a query which first checks if the record exists or not; if it exists, it should execute the update query and if it doesn't exist, it executes the insert query. how do i check if col3 is null and if it is null, it should execute the update query. .
$sql = "SELECT uid FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Not really checking a value of the column, but I don't think you actually need that.
You need to have uid as a UNIQUE column. You try to insert a row for a new user with the given uid; if it finds the user with the same uid, then you do the update instead.
UPDATE:
I guess you did not bother to read the link.
I did not test it, but it should be something like this:
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session='SeSsIoN_iD'
This will insert the user if he does not exist, and if he does, it will set a new session key. OR, if you want to preserve the old session key if he already has one,
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session=IFNULL(session, 'SeSsIoN_iD')
One query, not three. You were not already doing it.
$sql = "SELECT * FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
$res = mysql_fetch_array($sql);
if(!empty($res['col3'])) {
insertUser($user_id,$sk, $conn);
}
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
Is this what you mean?
If the record does not exist -> insert.
If the record does exist and its col3 is null -> update
If the record does exist, but its col3 is not null -> do nothing?
That could be achieved like this (untested):
$sql = "SELECT uid, col3 FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
$col3value = mysql_result($result, 0, 'col3');
if (is_null($col3value))
{
updateSessionKey($user_id,$sk,$conn);
}
}