I am new in PHP .. I need help to make a PHP code to update data in MySQL if data exists and if don't already exists then insert data in MySQL.. I have made the PHP code to do this but it's inserting data when data already exists.. in MySQL.. Please help
$con = mysql_connect('localhost','root','root');
$db = mysql_select_db('gamingtracker',$con);
$query = "SELECT * FROM servers WHERE sgame='$game_insert'";
$result = mysql_query($query, $con);
While($row = mysql_fetch_array($result)) {
$id = #$row['id'];
$sname = #$row['sname'];
$sgame = #$row['sgame'];
$minplayers = #$row['minplayers'];
$maxplayers = #$row['maxplayers'];
$ip = #$row['ip'];
$port = #$row['port'];
$map = #$row['map'];
}
$sname1= html_entity_decode("{$server['s']['name']}");
if(#$sname=="{$server['s']['name']}"
AND #$sgame=="{$server['s']['game']}"
AND #$minplayers=="{$server['s']['players']}"
AND #$maxplayers=="{$server['s']['playersmax']}"
AND #$ip=="{$server['b']['ip']}"
AND #$port=="{$server['b']['c_port']}"
AND #$map=="{$server['s']['map']}" )
{
$query1 = "UPDATE servers
SET sname='$sname1', sgame='{$server['s']['game']}', minplayers='{$server['s']['players']}', maxplayers='{$server['s']['playersmax']}', ip='{$server['b']['ip']}', port='{$server['b']['port']}', map='{$server['s']['map']}'
WHERE ip='{$server['b']['ip']}', port='{$server['b']['port']}', sgame='{$server['s']['game']}'";
$result1 = mysql_query($query1, $con);
}
else {
$query1 = "INSERT INTO servers (id,sname,sgame,maxplayers,minplayers,ip,port,map) VALUES ('','$sname1','{$server['s']['game']}','{$server['s']['players']}','{$server['s']['playersmax']}','{$server['b']['ip']}','{$server['b']['c_port']}','{$server['s']['map']}')";
$result1 = mysql_query($query1, $con);
}
So you only want one entry per unique combination of ip, port, and sgame? The most straightforward way would be to let mysql handle this.
First, create a unique index on the table for those fields. Run the following in mysql:
CREATE UNIQUE INDEX ip_port_sgame ON servers (ip, port, sgame);
Then, instead of running an INSERT query, use REPLACE. So just change this one line in your php:
UPDATE servers
to
REPLACE INTO servers
Related
Basically, I have two identical tables in SQL Server and MySQL. I want to use PHP in such a way that I'll only have to manually insert new values in one of them. I want to make a PHP code where the newly inserted values in the SQL Server table will also be inserted in its identical counterpart in MySQL with the press of a button.
For example, I have a table named "Customers" in both SQL Server and MySQL with the rows "ID (auto incremented)", Name, and Address. I insert new values into those columns in SQL Server. How do I make it so that I'll only have to press a button made in PHP so that I won't have to do the whole "insert into" process again in MySQL?
Any ideas are much appreciated!
According to new information given in the comments, I'm changing my answer and adjusting the code.
Code example:
<?php
$serverName = "server"; //serverName\instanceName
$connectionInfo_mssql = array("Database"=>"DB", "UID"=>"username", "PWD"=>"password","CharacterSet"=>"UTF-8");
$conn_mssql = sqlsrv_connect($serverName, $connectionInfo_bi);
$conn_mysql = new mysqli("server", "username", "password", "db");
//SELECT FROM MS SQL DB
$mssql_array = array();
$ms_sql = "SELECT column_names FROM db_table";
$mssql_query = sqlsrv_query($conn_mssql , $ms_sql);
while($row = sqlsrv_fetch_array($mssql_query) {
$mssql_array[] = array('name' => $row['name'],
'adress' => $row['adress']);
}
foreach($mssql_array as $key => $value) {
//SELECT FROM MySQL DB
$my_sql = "SELECT column_names FROM db_table WHERE name = '".$value['name']."' AND adress = '".$value['adress']."'";
$mysql_query = mysqli_query($conn_mysql , $my_sql);
$num_rows = mysqli_num_rows($mysql_query);
if ($num_rows == 0) {
//Insert in MySQL DB
$sql = "INSERT INTO db_table (db_columns) VALUES (variables_from_array)";
$sql_query = mysqli_query($conn_mysql, $sql);
} else {
//There is a record in DB, and maybe you want to update it. If not, then lose this else part.
}
}
echo 'Table Customers from MS SQL DB and table Customers from MySQL DB are now synced!';
?>
I'm trying to retrieve multiple data from a database with a PHP function, but somehow when I do this multiple times it gives a MySQL connection error.
$heat=getStat("heat", $userid);
$cash=getStat("cash", $userid);
echo mysql_error();
I use the code above to assign variables by calling a function which retrieves the stats from a database.
When I use the above codes separately, they work. But when I put them together they fail.
Is this a simple you-are-a-beginner-noob-programming-mistake?
I forgot to post the function so here it is:
function getStat($statName,$userID) {
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to MySQL' . mysql_error());
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
The problem is most likely caused by the require_once. As this is where you are pulling in your config for the database connection. The second time the require is executed it will not pull in the code required to define your database connection vars.
As #MichaelBerkowski has stated, it would be much better to have one global connection when the script loads, and make use of this connection for each request to the database. However if you wish to stick with the way you have currently, this should solve the problem:
function getStat($statName,$userID) {
require 'config.php'; /// <-- note this has changed to just require
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die ('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT value FROM user_stats WHERE stat_id = (SELECT id FROM stats WHERE display_name = '%s' OR short_name = '%s') AND user_id = '%s'",
mysql_real_escape_string($statName),
mysql_real_escape_string($statName),
mysql_real_escape_string($userID));
$result = mysql_query($query);
list($value) = mysql_fetch_row($result);
return $value;
}
So I am trying to download JSON into an iOS application and I don't really know a lot about PHP.
Currently I'm using a generic php scrip as a delegate that connects the the MySQL database and returns JSON results.
<?php
$host = "localhost"; //database host server
$db = "***"; //database name
$user = "root"; //database user
$pass = "root"; //password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db("***", $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM table";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The issue with this is that I don't want to encode the entire table in JSON I just want to return a few select data fields from the particular table so I don't download unnecessary data.
I know that you do this in the SELECT query but something is wrong with my syntax for this.
I had been trying with:
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
but that doesnt seem to be working.
Also, In that table there are two separate data fields that are used to build a URL for an image, and Im not sure how to combine the two here so that they are returned in the JSON as one field.
For example: I Have a base string
"http://wwww.mysite.com/"
and i would like the add the two data Fields to that string so that when it returns the JSON objects they have those fields already concatenated so that the app can just use that URL:
"http://wwww.mysite.com/[data field1]/[datafield2]"
The query you should be trying looks like
$query = "SELECT col1,col2 FROM table";// no need of asterisk if you mention col names
Now if you need to combine two columns there itself in the query, try something like
$query = "SELECT CONCAT('mysite.com/',col1,'/',col2) FROM table";
"/" is the separator between two columns.
The query to fetch individual cols is
select col1,col2,col3 from table_name
No need to provide * like you did
$query = "SELECT *[datafield],[otherdatafield],... FROM table";
^........here * is causing the problem.
I'd like to insert data into a table only when certain values in that table's (sessionid) row match another variable. I am struggling to put together the INSERT statement. The approach I am taking: retrieve all the rows in the table that match the criteria (retailer=$retailer) and then iterate through those rows inputting the variable options into the sessionid table.
$retailer = $_GET['retailer'];
$options = $_GET['options'];
$session = session_id();
//mysql connection stuff goes here
$query = "
SELECT *
FROM `sessionid`
WHERE `retailer` = '$retailer'
";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
mysql_query("INSERT INTO sessionid (options) VALUES('$options')");
}
Is the syntax correct for me to do this? Thanks!
Are you maybe looking for the UPDATE command instead?
UPDATE sessionid
SET options = $options
WHERE retailer = $retailer
By the way, I would look in to using PDO as it's more secure than pushing $_GET values in a database.
$db = new PDO('mysql:host=localhost;dbname=MYDATABASE', 'username', 'password');
$db->prepare('UPDATE sessionid SET options = ? WHERE retailer = ?');
$db->execute(array($options, $retailer));
You can use the WHERE clause in mysql to do this. If you are changing an existing row, you actually want UPDATE, not INSERT.
UPDATE sessionid SET options=$options where retailer = $retailer
i have two kind of database in different server. And the script below is to make DB connection:
//DB 1
define("DBNAME","xx.xxx.xx.xxx:D:\DATABASE\OCS DATA.FDB");
define("DBUSER","USER");
define("DBPASS","USER");
$dbh = ibase_connect(DBNAME,DBUSER,DBPASS) or die(_ERROR15.": ".ibase_errmsg());
//DB 2
$dbc=mysql_connect(_SRV, _ACCID, _PWD) or die(_ERROR15.": ".mysql_error());
mysql_select_db("qdbase") or die(_ERROR17.": ".mysql_error());
beside that,i have some query for insert data into another DB:
//if structure of the both tables are same then...
$sql = "insert into database1.member select * from database2.member";
//if structure of both tables are not same then
$sql = "Insert into database1.member select columnname1,columnname2 ".
"from database2.member";
whether this query can be use for the condition like above, which have two different type of DB? if it so, which part that must be changed?
while ($ibase_row = ibase_fetch_assoc($rResult)){
$ins = array();
foreach ($ibase_row as $col => $val){
$ins[$col] = mysql_real_escape_string($val);
}
$mysql_insert = "INSERT INTO qdbase.table SET ".implode(',', $ins);
$res = mysql_query($mysql_insert, $dbc) or die();
}
There is a chance that your database systems support "dblink" feature.
If this is available you would link the mysql to Firebird or vice versa and run the script from one of them.