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.
Related
I'm using the SQL Server drivers for PHP to access a SQL Server database and I have a problem to update some data using sqlsrv_prpare and sqlsrv_execute functions.
I'm running two queries:
In the first query I'm retrieving some binary data (In SQL Server Management Studio, this query takes about 15 minutes to getting completed);
Then, for each row returned by the first query execution I'm trying to Update some data on the database.
Here's how my code looks like:
$query1 = "SELECT tgt.id, src.file, src.field1 from [Table1] tgt inner join [Table2] src on tgt.id = src.id order by tgt.id";
$query2 = "UPDATE [Table1] SET field1 = ? WHERE id = ?";
$getFiles = sqlsrv_query($con, $query1); //$con is the connection with the database, received by parameter
while($row = sqlsrv_fetch_array($getFiles, SQLSRV_FETCH_BOTH)) {
/* Some code here */
$file = $row[1];
$value = $row[2];
try {
if(!is_null($file)) {
$stmt = sqlsrv_prepare($con, $query2, array(&$value, &$row[0]));
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
sqlsrv_execute( $stmt );
}
} catch (Exception $e) {
error_log("\nError: " . $e->getMessage());
}
} //end while
sqlsrv_free_stmt($getFiles);
sqlsrv_close($con);
The problem is that the code inside the loop works fine to the first row, but on the second the update query isn't executed. The sqlsrv_prepare returns the value 1, but the sqlsrv_execute doesn't returns anything.
I'm thinking that the problem could be related to the first query execution time, but I don't know how to check this, considering that no error log is generated, the script just keeps executing forever.
EDIT: Actually, the example was simplified. The values that will be updated on tgt table are calculated using some data that are in src table and other application data. That's the reason why I use the loop, for each row returned by query1 specific values are calculated and used on query2. I already checked that these values are correctly calculated, this is why I thought it's better to simplify the example.
To solve this problem I have to ran the queries separately:
First I ran the query1, made the computation of the data that I needed to update the tgt table and stored them in an array;
Then, using the data stored in array, I ran the query2.
No other changes were needed.
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 a newbie Programmer here, I want to know why my code does not get the correct data from my Mysql DB.
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '$player'");
If I use this code, then I get the $playerbal as Resource id #7
I have found some solutions for this Resouce id #7 error. If I use mysql_fetch_array, I get just "Array"
mysql_* functions are now deprecated and shouldn't be used anymore.
Your code isn't working because you need to use mysqli_fetch_array() in order to retrieve the actual data in the table using a DB connection handler
Try using something like this :
//Create DB connection
$con=mysqli_connect("localhost","root","password","Torch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con, "SELECT money FROM table WHERE name = '$player'") or die(mysqli_error($con));
//Retrieve the info(row) from the retrieved recordset and loop through it
while($row = mysqli_fetch_array( $result )) {
//Retrieve the needed field from the row
$data=$row['money'];
//do your stuff here
}
//Close connection
mysqli_close($con);
BTW Don't forget to sanitize your inputs.
mysql_query() statement returns a resource pointer to the result set, not the data itself. You'll need to use mysql_fetch_array() in order to retrieve the actual data in the table.
here's the sol
$row = mysql_fetch_array($playerbal);
$data = $row['money'];
echo $data;
If you want to get all rows of money column then use this code-
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '{$player}'");
while($data = mysql_fetch_array($playerbal)){
echo $data[0]; //there is only one column so this column is stored into 0 index.
}
I am using this library from Twilio to send multiple numbers SMS.
https://www.twilio.com/docs/quickstart/csharp/sms/sending-via-rest
I have a mysql database and a table (called contacts) with the following attributes:
1. Name
2. Number
Instead of using a For While loop and read the full script for each number, I want to use an array as shown in the above link.
How do I make an array in PHP with the data pulled in from the table instead of a manual insert?
From Twilio
var people = new Dictionary<string,string>() {
{"+14158675309","Curious George"},
{"+14158675310","Boots"},
{"+14158675311","Virgil"}
};
My code
$sql = "SELECT * from contacts";
$result = mysql_query($sql,$con);
var people = new Dictionary<string,string>() {
mysql_fetch_array($result)
};
I need numbers and names associated within the array.
why not :
$sql = "SELECT * from contacts";
$result = mysql_query($sql,$con);
var people = new Dictionary<string,string>()
for each($result as $contact)
{
//Add $contact['Name'], $contact['Number'] to dictionary.
//or if you use an array instead of a dictionary.
// $tab['number']=$contact['Number'];
// $tab['name']=$contact['Name'];
// array_push($people,$tab);
}
return $people;
?
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.