How can insert value to specific row in database - php

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.

Related

How to loop through each item in database

I have a PHP script I'm writing where I have to get data from a database and convert the results into a static HTML page. I'm trying to loop through all the items 1 by 1 in a particular database and grab the value that's in their "nid" column as I go along. I started the script. I have the database connection. Just stuck on how I should do the loop. Should it be a while loop or a for loop? If so how do I go about looping through the items in the table 1 by 1 and grabbing a particular column value? Also attached is the screenshot of the database so you can see the column I'm trying to target.
<?php
// Establish all database credential variables
$serverName = "localhost";
$username = "admin";
$password = "peaches";
$databaseName = "static_site";
// Create Database Connection
$connection = new mysqli($serverName, $username, $password, $databaseName);
// Check Database Connection
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
} // line ends if statement
$queryNodeRevision = "SELECT nid FROM node_revision";
// line above creates variable $queryNodeRevision > selects column "nid" from table "node_revision"
$dataBaseQueryResults = mysqli_query($connection, $queryNodeRevision);
// line above creates variable $dataBaseQueryResults > actually queries the database and passes in 2 variables
// passes in database connection variable and variable that selects "nid" column from "node_revision" table
?>
Use while loop and mysqli_fetch_array to fetch the value of nid for each row.
$queryNodeRevision = "SELECT nid FROM node_revision";
$results=mysqli_query($queryNodeRevision);
while ($row = mysqli_fetch_array($results)) {
echo $row['nid'];
}

INSERT table row to another table

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'";

prevent duplicate entries mysql

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.

Inserting data MySQL

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.

PHP/MYSQL - Check whether it have duplicated record before inserting new record

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

Categories