I have an .xml page that i want to pull data from every 6 hours.
this data is then inserted into the database and the unique Key is set as "characterID".
the code then need to check for the following an perfom an action based on its results.
If the .XML file contains characterID not already in database add the row!
If the database contains a characterID NOT in the .XML remove row!
If a row in the .XML file is different (THE CHARACTERID wont be different but other data will) to the row in the database UPDATE the row with new information WHERE charactedID is the same!
this is my current source code which loops through the XML and inserts the data correctly but i cannot update the information.
<?php
// INCLUDE DB CONNECTION FILE
include("includes/connect.php");
// CHANGE THE VALUES HERE
include("includes/config.php");
// URL FOR XML DATA
$url = "test.xml"; // For Testing Purposes
// RUN XML DATA READY FOR INSERT
$xml = simplexml_load_file($url);
// RUN SQL to check data already in table
$sql = mysql_query("SELECT * from `ecmt_memberlist`");
// Loop Through Names
foreach ($xml->result->rowset[0] as $value) {
$characterID = mysql_real_escape_string($value['characterID']);
$name = mysql_real_escape_string($value['name']);
$startDateTime = mysql_real_escape_string($value['startDateTime']);
$baseID = mysql_real_escape_string($value['baseID']);
$base = mysql_real_escape_string($value['base']);
$title = mysql_real_escape_string($value['title']);
$logonDateTime = mysql_real_escape_string($value['logonDateTime']);
$logoffDateTime = mysql_real_escape_string($value['logoffDateTime']);
$locationID = mysql_real_escape_string($value['locationID']);
$location = mysql_real_escape_string($value['location']);
$shipTypeID = mysql_real_escape_string($value['shipTypeID']);
$shipType = mysql_real_escape_string($value['shipType']);
$roles = mysql_real_escape_string($value['roles']);
$grantableRoles = mysql_real_escape_string($value['grantableRoles']);
// NOW LETS INSERT INTO DATABASE!!
$query = "INSERT INTO `ecmt_memberlist` SET
characterID='$characterID',
name='$name',
startDateTime='$startDateTime',
baseID='$baseID',
base='$base',
title='$title',
logonDateTime='$logonDateTime',
logoffDateTime='$logoffDateTime',
locationID='$locationID',
location='$location',
shipTypeID='$shipTypeID',
shipType='$shipType',
roles='$roles',
grantableRoles='$grantableRoles'";
//echo query to error check
echo $query;
echo "<br><br>";
mysql_query($query) or die(mysql_error());
};
?>
the table this gets inserted into will also hold some other information that will be associated with the characterID hence the need to "NOT REMOVE ROW AND REPLACE" else i will loose the associated data in that row when added manually.
You could first do a SELECT statement with the CharacterID. Than you can check if the rowcount is equal to 1. If this is the case you can update your row, otherwise you insert a new row in the database.
Related
What's wrong with the following syntax:
if( isset($_POST['save_changes']) ) {
// Get current id of customer
$currentID = $_GET['id'];
// Get Input Values
$newfirstName = validateInputData($_POST['first_name']);
$newlastName = validateInputData($_POST['last_name']);
$newemail = validateInputData($_POST['email']);
$newphone = validateInputData($_POST['phone_number']);
$newaddressOne = validateInputData($_POST['address_one']);
$newaddressTwo = validateInputData($_POST['address_two']);
$newcounty = validateInputData($_POST['county']);
$newcity = validateInputData($_POST['city']);
$newzipCode = validateInputData($_POST['zip_code']);
$newprovince = validateInputData($_POST['province']);
$newstate = validateInputData($_POST['state']);
// Queries
$query = "UPDATE customers
SET
first_name='$newfirstName',
last_name='$newlastName',
email='$newemail',
phone='$newphone'
WHERE id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
$query = "UPDATE addresses
SET
address_one='$newaddressOne',
address_two='$newaddressTwo',
county='$newcounty',
city='$newcity',
province='$newprovince',
zip_code='$newzipCode',
state='$newstate'
WHERE customer_id='$currentID'
";
$conn->query($query) or die($conn->error.__LINE__);
// Bring user back to index
header("Location: index.php?alert=savechanges");
// Close connection to database
$conn->close();
}
the above query runs fine, but the row is not updated. all the field names are appropriate. When the query is tried in phpMyAdmin, row updated.
Please help, thank you.
Your validateInputData() function is not doing any validation. Hopefully it's doing some escaping, implying that you are assuming global scope for your database connection object. You didn't tell us what type of database object this is. Your error checking is poor. You don't do an explicit exit after the redirect.
Apart from that the sql looks ok.
When I'm trying to perform basic CRUD operation on my database, but here when I tried to get a single row from my database whit a php script, I see the correct data from my database, but when I'm put more rows on de data base, and I tried to get the data, it never appears.
I'm using this PHP Script
<?php
//Importing Database Script
require_once('Connectdb.php');
//Creating sql query
$sql = "SELECT * FROM ensaladas ";
//getting result
$r = mysqli_query($con,$sql);
//creating a blank array
$result = array();
//looping through all the records fetched
while($row = mysqli_fetch_assoc($r)){
//Pushing name and id in the blank array created
array_push($result,array(
"ensid"=>$row['ensid'],
"nombre"=>$row['nombre'],
"precio"=>$row['precio'],
));
}
//Displaying the array in json format
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
And gives me the next result:
I use this when the table has 2 rows, and when I put another rows, the code stop Working. The table of the database has 3 fields: ensid,nombre,precio. As you can see here:
PD: I'm using this script to get the data on an Android APP
Error checking
Do some error checking on your part. You can also try to run the query at the back-end of your system (PhpMyAdmin).
Fetching data
Since you are using mysqli_* API already, try using prepared statement instead:
$stmt = $con->prepare("SELECT ensid, nombre, precio FROM ensaladas");
$stmt->execute();
$stmt->bind_result($ensid, $nombre, $precio);
while($stmt->fetch()){
array_push($result, array(
"ensid"=>$ensid,
"nombre"=>$nombre,
"precio"=>$precio,
));
}
$stmt->close();
Displaying the data
You can then now display all the data using:
echo json_encode($result);
Or if you want a specific row from the result, you can use an index:
echo json_encode($result[$x]); /* $x REPRESENTS THE INDEX; INTEGER VALUE */
Or get a specific data from a specific row:
echo json_encode($result[$x]['ensid']); /* EITHER ensid, nombre, or precio */
When I took a look into your database selection example(screen), the table name that you are querying is 'bebidas', while in the screenshot of the database you have used 'ensaladad'.
Try to use:
// Creating SQL query
$sql = "SELECT * FROM ensaladas ";
or use:
// looping through all the records fetched
while($row = mysqli_fetch_assoc($r)){
// Pushing name and id in the blank array created
array_push($result,$row));
}
I am working with jstree. The tree works fine.I send JSON to a PHP file with JQuery. This works fine.
$("#button3").click(function(){
//json object
var objtree = $("#container").jstree(true).get_json('#', { 'flat' : true });
var fulltree = JSON.stringify(objtree);
var myarray = $.parseJSON(fulltree);
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
//sending to php file
$.post('update.php',{ data: paramJSON });
});
Then in the php file (update.php), I update mySQL table by: deleting all the records in $tablename ($sql1) and inserting the information gotten from the JSON ($sql2). This works fine.
<?php
$connection = mysqli_connect($servername, $user,$password,$database) or die("Error " . mysqli_error($connection));
$test = $_POST["data"];
$obj = json_decode($test, true);
$data = $obj["myarray"];
//first query
$sql1 = "DELETE FROM $tablename";
$connection ->query($sql2);
foreach($data as $val){
//second query
$sql2 = "INSERT INTO $tablename(id,parent,text) VALUES('".$val['id']."', '".$val['parent']."', '".$val['text']."')";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
}
mysqli_close($connection);
?>
But what I want is not to delete everything in the table then insert them brand new. But an SQL statement to update the old values (using the id maybe?) and insert the new values.
So like:
If id exists:
update row
else:
insert new row
I am new to PHP and SQL. So my problem is knowing the PHP syntax for accessing JSON array information. So please any example would be much appreciated!
First, you'll use a PHP function to get all rows matching the given ID. if this returns one, you'll use another function to UPDATEwhere the ID == valueFromPreviousFunction, else you'll call a function to INSERT a new row.
$check = mysqli_query($connection,"SELECT * FROM `your_table_name` WHERE `id`='".$val["id"]."'");
if(mysqli_num_rows($check)==1)
{
//Update the row
$update = mysqli_query($connection,"UPDATE `table_name` SET `parent`='".$val["parent"]."', `text`='".$val["text"]."' WHERE `id`='".$val["id"]."'");
}
else
{
//Insert the row
}
There isn't a command to do what you want in a single operation.
You should either fetch all ids beforehand and run an update for each one of them separately, or use REPLACE INTO.
Be careful with REPLACE INTO, though: if a row matching a primary/unique key exists, it first deletes it and then inserts a new one rather than updating the existing row.
I have a MySQL table with the following fields:
ID
PHONE
NAME
CITY
COUNTRY
Using PHP, I am reading a comma separated dump of values off a text document, parsing the values and inserting records to the table. For reference, here's the code:
<?php
// Includes
require_once 'PROJdbconn.php';
// Read comma-separated text file
$arrindx = 0;
$i = 0;
$filehandle = fopen(PROJCDUMPPATH.PROJCDUMPNAME,"rb");
while (!feof($filehandle)){
$parts = explode(',', fgets($filehandle));
$contnames[$arrindx] = $parts['0'];
$contnumbers[$arrindx] = preg_replace('/[^0-9]/','',$parts['1']);
$arrindx += 1;
}
fclose($filehandle);
$arrindx -= 1;
$filehandle = NULL;
$parts = NULL;
// Build SQL query
$sql = "INSERT INTO Contact_table (PHONE, NAME) VALUES ";
for ($i = 0; $i < $arrindx; ++$i){
$sql .= "('".$contnumbers[$i]."', '".$contnames[$i]."'),";
}
$i = NULL;
$arrindx = NULL;
$contnames = NULL;
$contnumbers = NULL;
$sql = substr($sql,0,strlen($sql)-1).";";
// Connect to MySQL database
$connect = dbconn(PROJHOST,PROJDB,PROJDBUSER,PROJDBPWD);
// Execute SQL query
$query = $connect->query($sql);
$sql = NULL;
$query = NULL;
// Close connection to MySQL database
$connect = NULL;
?>
Now, this code, as you can see, blindly dumps all records into the table. However, I need to modify the code logic as such:
Read text file and parse records into arrays (already doing)
For each record in text file
Check if PHONE exists in the table
If yes,
For each field in the text file record
If text file field != NULL
Update corresponding field in table
Else
Skip
If no,
INSERT record (already doing)
I apologize if the logic isn't terribly clear, feel free to ask me if any aspect confuses you. So, I understand this logic would involve an insane number of SELECT, UPDATE, and INSERT queries, depending on the number of fields (I intend to add more fields in future) and records. Is there any way to either somehow morph them into a single query or leastwise optimize the code by minimizing the number of queries?
What you're trying to do is called an "upsert" (update/insert).
MySQL INSERT else if exists UPDATE
I am trying to grab ad code from my database and echo it on to the page, but for some reason it is not showing up?
$getad = ("SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ");
while($rows = mysql_fetch_array($getad))
{
$code = $rows['code'];
}
$ad1 = $code;
later down the page i print it like this.
<?php print $ad1 ?>
I think your problem is that you don't actually execute the query, you just have saved it in a variable ($getad) and then try to do a fetch af an array containing a string as I see it. If I remeber correctly you have to save you query in a variable, as you did, and then type
$getad = "SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ";
$q = $db->query($getad);
// generate results:
while ($q->fetchInto($row)) {
//display or store
}
You should also include checks, for example that this code has extracted at least one row, or that database connection is working, etcetera.