Hello guys I have a problem with a script
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'site';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die(mysql_error());
}
mysql_select_db($dbname, $con);
$sql = "REPLACE INTO stiri (id, titlu, continut, link, categorie, data) VALUES ('','$titlu','$text','$link','Liga 1','$data')";
mysql_query($sql);
mysql_close($con);
This part is in a php foreach part and every time I run the script I get duplicate entry, how can I prevent this?
I could use UNIQUE Constraint but I want the link to be unique which is longer than 125 chars..
I'm guessing id is a primary key field in your table? You're trying to insert an empty string ('') into it. If that's an INT field, mysql will convert '' into 0. After the first such insert, you'll run into the duplicate key problem.
Change id to be an auto_increment field, and insert a null value, e.g.
REPLACE INTO stiri (id, ...) VALUES (null, ....)
so mysql can generate an ID for you automatically.
Related
Let's say I have 2 tables in the database, first table is userregistration and 2nd table is userdetails. In table userregistration, the primary key that I use is called id and it is auto increment.
So let's say I have insert one user and the id of the user is 1, and then I want to insert the details of the said user, how do I make sure the id is also the same as in the userregistration table?
Already read about last_insert_id, but I can't understand how to use it.
Here is an example:
$server_name = ""; //Your server name
$user_name = ""; //Database Username
$password = ""; //Database Password
$database_name = ""; //Database Name
// Create a connection
$connnection = new mysqli($server_name, $user_name, $password, $database_name);
//Insert into First Table
$sql = "INSERT INTO user_registration (firstname, lastname)
VALUES ('Firstname', 'Lastname')";
if ($connection->query($sql) == TRUE) {
$last_inserted_id = $connection->insert_id;
//Insert into Second Table
$sql_two = "INSERT INTO user_registration (user_id, phone_no, address)
VALUES ($last_inserted_id, 1234567, 'Address')";
$connection->query($sql_two);
}
You must create a Foreign key reference in the second table. In this user_id is the Foreign Key.
i have PHP file that post data to database sequentially ( row by row ) using url , i want to know how can post data at specific row and if there is data in that row replace it by new value
<?php
$dbusername = "root";
$dbpassword = "root";
$server = "192.168.137.150";
$dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
$dbselect = mysql_select_db("test",$dbconnect);
$sql = "INSERT INTO test.a0 (a0) VALUES ('".$_GET["value"]."')";
mysql_query($sql)
?>
Depending on logic you need in the table, usually you have to look for the entry with SELECT first and then UPDATE if exists or INSERT if missing (2 queries required: SELECT + UPDATE/INSERT).
You can also make that field key and directly use INSERT ... ON DUPLICATE KEY UPDATE in a single query.
I have two identical tables in my database. I'm trying to ask the user the package number, then when the user clicks a button, it will copy the row matching the user input to another table.
My tables are:
awb - where the original data is.
temp - table to insert the data into.
Here's my code:
$dbhost = "localhost";
$dbuser = "root";
$dbname = "outbound";
mysql_connect($dbhost, $dbuser);
mysql_select_db($dbname) or die(mysql_error());
$packNO = $_GET['packNO'];
// Escape User Input to help prevent SQL Injection
$packNO = mysql_real_escape_string($packNO);
//build query
$query_add="INSERT INTO temp FROM awb WHERE packNO = '$packNO'";
#mysql_query($query_add);
$query = "SELECT * FROM temp";
$qry_result = mysql_query($query) or die(mysql_error());
The code that follows outputs the content of the temp table. But when I print it, I get nothing.
Why is the temp table empty when I print its values?
Try something like this
$query_add="INSERT INTO temp SELECT * FROM awb WHERE packNO = '$packNO'";
Documentation
Similar query, but not using *
$query_add="INSERT INTO temp (packNO, name)
SELECT packNO, name
FROM `awb`
WHERE `packNO` = '$packNO'";
I am a beginner in MySQL and I'm trying to enter some values in my database. The database is already made and its based localy.
I have a Schema named 'test' and within the schema I have a table named 'contacts'. Within the contacts I have an id, first and last name.
So I am trying to enter some data in the contacts. This is my php file:
<?
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
When I run the file on my browser, my database doesnt get any values. How can I execute that file so that John Smith gets added to my database?
Your php file has to start with <?php instead of <?.
Try this:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '*******'; // root pass
$db_database = 'contacts';
$link = #mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_database,$link);
$query = "INSERT INTO contacts VALUES ('','John','Smith')";
mysql_query($query);
mysql_close();
?>
Change
mysql_query($query);
to
mysql_query($query) or trigger_error(mysql_error() . $query);
then all will be revealed.
You might consider trying PHP ADODB and using AutoExecute with INSERT, if you know your field names
$db->AutoExecute('tablename',array('field1'=>'value','field2'=>'value'));
Can also be used for update:)
http://adodb.sourceforge.net/
First how is the structure of your table? If you have only 2 fields on the table that is the error if not please try to post the error the console gives back to you.
$query = "INSERT INTO contacts (first,last) VALUES ('John', 'Smith')";
$e=mysql_fetch_assoc($query);
also do not forget that your table structure says not null for the field id and the default value is null, so it will not accept this kind of insertion
Your ID is probably auto_increment, if so add order of attributes to your query :
INSERT INTO contacts(`first_name`, `last_name`) VALUES ('John','Smith')
Replace first_name and last_name with your real column names.
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source