How do I dynamically add to a JSON array in PHP - javascript

So I have the following JSON:
[{"username":"User1","password":"Password"},
{"username":"User5","password":"passWord"},]
Generated from:
<?php $username = $_POST["username"]; ?><br>
<?php $password = $_POST["password"]; ?><br>
<?php
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
$extra = array(
'username' => $username,
'password' => $password
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
print("working");
}
?>
After the user logs in they have the ability to make a post, how would I go about creating a post array for each user and how would I add to it dynamically ?
This is all I have and I have tried many different ways, but cant seem to figure out how to make it dynamic.
<?php
$urlText = $_REQUEST["urlText"];
$currentData = file_get_contents('UserJSON.txt');
$array_data = json_decode($currentData, true);
//for loop
$array_data[i]['Posts'] = $urlText;
//end for loop
$final_data = json_encode($array_data);
if(file_put_contents('UserJSON.txt',$final_data)) {
}
?>
In this situation though, posts is not an array, it just simply overwrites what already there.
[{"username":"User1","password":"Password","Posts:{"This is a post"}},
{"username":"User5","password":"passWord"},"Posts:{"This is a post2"}}]
Therefore, how do I add a posts array and how do I add to it dynamically ? I have not been able to figure such a simple thing out for a very long time

File get contents from like "posts/useridhere.txt", or allposts.txt
You will also need to use unique post IDs.
Json decode your posts JSON
Add post content to array
Json encode array
Write new json to the users post file
Ultimately I do not recommend this. If you want a paid internship I'll teach you how to use MySQL. We make websites :) but if you want to do it this way, you'll need a JSON file to store unique post IDs or even store all posts in one file. The problem is that you'll have a limit of how many posts can be stored in that single JSON array. I hope this answer is enough to help you. It's all the steps needed
$posts = file_get_contents($postsFile);
$posts = json_decode($posts);
$newPost = array(
"user"=>$user,
"postTitle"=>$string,
"text"=>$content
);
$posts[] = $newPost;
$newPostID = count($posts); // will not work properly (for linking posts) once you delete a post - you need unique post ids generated!
$posts = json_encode($posts);
// Overwrite your posts file with $posts. It will have all posts you need :)

Related

Pull mySQL data via PHP into an array of Javascript objects

i am trying in pull my data from mySQL and convert it to a format I can then pass to google.maps API. I am thinking mySQL -> php -> javascript -> google.maps makes the most sense but am deffinitly open to other suggestions.
So far I have connected to and successfully queried my data into an array
<?php
//library of mysql functions including linkDB()
include('../sqlFunctions/sqlFunctions.php');
//Establish connection to database
if($link = linkDB()){
echo "connected to DB";
}
//set up a MySQL query. I am simply pulling geocoordinate ints, strings and boolean.
$sql = "SELECT title
,lat
,lng
,titleYou
,descriptionAre
,privacyRockstar
FROM shelters;";
if($results = $link->query($sql)){
echo "<p>Query succsessful.</p>";
}else{
echo "Query Failed";
}
//initialize an array to store data
$rows = array();
while ($data = $results->fetch_assoc()) {
$rows[] = $data;
echo "<br><br>Loop rotation: ";
var_dump($data);
}
echo "<br><p>The End of The Loop<p><br>";
var_dump($rows);
?>
Now I just need to convert this data into something usable I can pass to google.maps.
Before I was pulling JSON from a text file, which worked, but I want to flexibility and stability of a database. It was easy to parse into and array of Javascript Objects. Then I could just call the index and the property that I needed as you can see from this function I was using.
function setMarkers(){
for(i=0; i < jsonParsed.arrayOfObjs.length; i++){
//setting parameters to hand to google
var markerOptions = {
position : jsonParsed.arrayOfObjs[i].position,
map : mapCanvas,
description : jsonParsed.arrayOfObjs[i].title,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
};
//create marker
this ['marker' + i] = new google.maps.Marker(markerOptions);
}
}
Thank you for any light you can help shed on my issue.
It sounds like you already found your answer but I'll post for completeness.
Simply change your the var_dump($rows) line to json_encode($rows).
Read more about json_encode in the php docs.
You probably want to have two php files:
api.php file that emits Content-type: application/json
index.php file that emits Content-type: text/html and calls api.php
On the index page, you can make an AJAX call to your API endpoint and then use JSON.parse(response).

Trying to create a menu dynamically with php using preg_match_all to my server php documents

The project consists of a lateral menu, which contains all my blog entries.
In theory, the menu works this way: I get the <h1> title of each of my blog documents and his corresponding href, using php.
So each time i add a new blog entry, it appears in the menu automatically,
i did this using fopen and fread and saving the contents of each php document of my blog in a variable called $leer.
Then, i used Preg_match_all to search the title of each blog entry and display it on the menu. With this I can make the menu without having to add the links manually, also using scandir get the url.
The problem is that, when using preg_match_all in the array, gives me many incorrect results, obtaining the same <h1> title four times without explanation.
Here is the code:
$escanear = scandir ("/home/sites/thetoptenweb.com/public_html/post");
$tamanoArray = count($escanear);
So first, as you can see, i´m using scandir and count to get the number of pages.
for($i=2;$i<=$tamanoArray-3;$i++){
$abrirFichero = fopen($escanear[$i],"r");
$leer=fread($abrirFichero, filesize($escanear[$i]));
fclose($abrirFichero);
}
Then, i use a for loop and fread to read all my documents.
The loop is made to "scan" only the selected files between the second and the last-3, because those are my blog entries.
preg_match_all('%<h1>(.*)</h1>%', $leer, $arrayMaches);
So, with the preg_match_all function i get the Title of my documents in a multi-dimensional array, that array is giving me problems i think, because i tryed to read each result with foreach loops, but there are some blank results and i don´t know why this happens.
foreach ($arrayMaches as $result) {
foreach ($result as $key) {
}
}
$cortado=preg_split('%</?h1>%', $key);
echo "<li>".$cortado[0]."</li><hr>";
Finally, i used foreach loops to access to the multi-dimensional array of the preg_match_all. Then, i preg_splited the results to get the text without html tags and after that, displayed the results with echo.
Hope someone helps me recognizing the problem and, if possible, an explanation to the preg_match_all array because i don´t understand how it´s created. Suggestions admited.
If you know a better way to do this, i´ll happy to read it.
This is the entire code:
<?php
$escanear = scandir ("/home/sites/thetoptenweb.com/public_html/post");
$tamanoArray = count($escanear);
for($i=2;$i<=$tamanoArray-3;$i++){
$abrirFichero = fopen($escanear[$i],"r");
$leer=fread($abrirFichero, filesize($escanear[$i]));
fclose($abrirFichero);
preg_match_all('%<h1>(.*)</h1>%', $leer, $arrayMaches);
foreach ($arrayMaches as $result) {
foreach ($result as $key) {
}
}
$cortado=preg_split('%</?h1>%', $key);
echo "<li>".$cortado[0]."</li><hr>";
}
?>
Thanks.
Just use the DOM... you'll save yourself some trouble.
$menuData = array();
$iter = new DirectoryIterator('/home/sites/thetoptenweb.com/public_html/post');
foreach ($iter as $file) {
if ($file->isFile()) {
$filename = $file->getFilename();
$path = $file->getPathname();
$dom = new DOMDocument();
$dom->loadHtmlFile($path);
$titleNode = $dom->getElementsByTagname('h1')->item(0);
if ($titleNode) {
$title = $titleNode->nodeValue;
$menuData[$filename] = $title;
}
}
}
Now you have all the stuff in $menuData you can just loop over it and output the links, assuming that the filename is the appropriate URL. Alternatively, you could output the links in the loop directly but it's wiser to separate things. Create a function to get the data you need, and then use that data to output.
But an even better solution would be to pick a blog platform and use that, then spend your time writing an importer and adjusting look and feel to suit.

Dynamically insert new row using javascript, but how to save these multiple row in php/mysql

I have create multiple row by using javascript. Now how to save these row in mysql. I already using some type of code, its not working. here my code is
[http://jsfiddle.net/bb2pJ/]
and php code for adding these value.
`
include "config.php";
if(isset($_POST['submit']))
{
foreach ($_POST['code1'] as $key => $value)
{
$code1 = $_POST["code1"][$key];
$product1 = $_POST["product_name1"][$key];
$qty = $_POST["quantity1"][$key];
$rate = $_POST["amount_name1"][$key];
$total = $_POST["total_name1"][$key];
$sql = mysql_query("insert into testing(code,product,qty,rate,total)values('$code1','$product1','$qty1','$rate1','$total1')")or die(mysql_error());
}
}
?>`
From you Js fiddle code, you are trying to post array of values for each field (ie code, proddname, ...).
How are submitting these values? If not passing through ajax post, then you need to declare fields names like code[], product_name[] ... as array for all fields so they will be submitted as array.
Rest code you have writtten above should work by using proper field name like code for code[] ... .
Please put proper spacing between your keywords and values/fieldname in your insert into.. statement.

Deleting forum posts

I have a table with the following fields: wall_posts, group_id, id, and user_id.
Wall_posts is user entries, group_id is imported from another table and is just a unique group id, id is just a simple counter, and user_id gets the user id from the session.
My code gets rid of all the wall_posts if you press the delete button by comparing the user id to the user in session. I'm trying to find a way to delete individual posts and not all the posts by the user.
Here is the code:
if (isset($_POST['delete'])) {
$current_user = $_SESSION['user_id'];
$result = mysql_query("SELECT * FROM group_posts");
while ($user_id = mysql_fetch_array($result)) {
$id = $user_id['user_id'];
}
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE $current_user = $id") or die(mysql_error());
}
}
How can I bound the delete button to individual posts instead of deleting all the posts made by the user currently in session?
Your SQL query above doesn't make sense - the WHERE statement should be in the form WHERE column_name = value.
Assuming id is the primary key for group_posts, as you're displaying posts, create a link for each post created by the author, e.g. Delete This Post for post with id 3. Then you'd do a query like this:
DELETE FROM group_posts WHERE id = postIdValueHere
Using the code pattern you have above:
if (isset($_POST['delete']) && $_POST['delete'] > 0) {
$current_user = $_SESSION['user_id'];
$post_id = (int) $_POST['delete'];
if ($current_user == $id) {
mysql_query("DELETE FROM group_posts WHERE id = $post_id AND user_id = $id") or die(mysql_error());
}
That query ensures that only posts with a given ID, created by the current author, can be deleted.
Does that answer your question?
Once you get more comfortable with SQL, you might also want to look into using prepared statements with mysqli or PDO. That will help your code clean and secure.
I'm assuming your delete buttons are simple links. Your links must contain all the information to delete a post. One way would be to pass a post id as a GET variable (e.g. link="myurl.com/posts/delete?id=#").
Your script would then at first make sure the current user is allowed to delete the post. For example:
$user_id = $_SESSION['user_id'];
$post_id = (int) $_GET['id'];
if(canDelete($user_id, $post_id))
{
// assuming post_id is unique for every post
$sql = sprintf("DELETE FROM group_posts WHERE id = %d", $post_id);
mysql_query($sql);
}
Of course, you'd have to implement canDelete($user_id) yourself.
By the way, "DELETE FROM group_posts WHERE $current_user = $id" always deletes every record in your table. At first you're comparing if $current_user equals $id and if they do happen to be equal, your query would look something like WHERE 1 = 1. I think you mean "DELETE FROM group_posts WHERE user_id = '$id'"
EDIT: It seems you want to use ajax for deleting your posts. I recommend using jQuery or any other proper javascript framework as it saves you time. Here is a link from the jQuery documentation describing how to make an ajax call to the server and a similar question to help you understand better.

Authenticating and using a Google Spreadsheet as a database for a web app

There seem to be many questions in around this topic but none seem to answer my question. I have a simple website with a signup form, and when users enter their email I want to push this as a new row in a Google Spreadsheet I have already setup. I don't want the user to authenticate or even know about this spreadsheet. How do I authenticate so I can start using the Google API? Code/pseudocode would be greatly appreciated! Here are some examples that do not answer my question:
Using Google Spreadsheet as DB for apps
Google spreadsheet as db for web applications
Here's a link to a library for accessing Google Spreadsheets:
https://github.com/EastCloud/node-spreadsheets
Note: Ive not actually used this lib
You will need to use PHP and the Zend GData Library.
When you post your form to your PHP script, you'll need to collect all of the variables into an associative array that you then pass to the insertRow method of Zend_Gdata_Spreadsheets.
It's important to note that your spreadsheet must contain column headers for my example to work. E.g. First Name / Last Name and it's important to note that when you target these column headers in a script, they will need to be all lowercase and stripped of spaces because this is how the spreadsheet expects them.
Here is a basic example of the PHP script:
<?php
$errors = array(); // use this to create an associative array to json encode and send back any errors
$rowData = array(); // this will be the associative array that gets passed to the insertRow method
$firstName = $_POST['firstName'];
if(isset($firstName)){
$rowData['firstname'] = $firstName; // note the key 'firstname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['firstname'] = '1';
}
$lastName = $_POST['lastName'];
if(isset($lastName)){
$rowData['lastname'] = $lastName; // note the key 'lastname' must equal the column header in your spreadsheet which you are inserting the value into. the column header name key should be all lowercase and not contain spaces regardless of if you have it in the spreadsheet
}else{
$errors['lastname'] = '1';
}
set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/');
$spreadsheetKey = 'your-spreadsheet-key';
$worksheetId = 'your-worksheet-id'; // if you only have one worksheet this will be 'od6'
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
$user = "your-user-name-at-gmail-dot-com";
$pass = "your-password";
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);
$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetKey);
$feed = $spreadsheetService->getWorksheetFeed($query);
global $spreadsheetService,$spreadsheetKey,$worksheetId,$rowData;
$insertedListEntry=$spreadsheetService->insertRow($rowData,$spreadsheetKey,$worksheetId);
$returnObject['success'] = 'true';
echo(json_encode($returnObject));
?>
Let me know if this works for you.

Categories