How to pass an array to a function as argument [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I made this code where I define an array, fliepath, in which I store the locations of some files.
include 'last_file.php'; // Include the function last_file
$last_file = last_file(); // assign to the function a variable and call the function last_file
// Connect to the database
include('connect_thesis.php');
// Defining an array, which has the three paths to the three different gps receivers
$file_path[0] = "/Applications/MAMP/htdocs/php_test/check/".$last_file[0];
//echo $file_path[0]; echo "<br>";
$file_path[1] = "/Applications/MAMP/htdocs/php_test/check2/".$last_file[1];
//echo $file_path[1]; echo "<br>";
$file_path[2] = "/Applications/MAMP/htdocs/php_test/check3/".$last_file[2];
//echo $file_path[2]; echo "<br>";
Then I made a function called insert() which I want to take as input the $file_path[0]:
function insert($file_path){
$fh = fopen($file_path,'r') or die ("Could not open:".mysql_error()).......;
I call the function from the main script as:
insert($file_path[0]);
I am new in programming and I am sure somewhere I am missing something basic!
The problem is that the function doesn't run!!!
Can you help me?
Thanx
D.
I THINK I DONT PASS CORRECTLY THE VALUE TO THE FUNCTION. CAUSE I GET NOTHING AS AN ERROR!

A few points to note:
You are calling insert using only the index 0, consider using a foreach and call the function on each items in your array.
insert() -> we are missing part of the implementation, but if the file exists, you should not get an error. Keep in mind that you need to close files that you open.
or die -> it looks like you copy pasted code from elsewhere... mysql_error() will not help you much as you're dealing with files at the moment. Consider changing it to
$fh = fopen($file_path,'r') or die ("Could not open:".$file_path)
You should probably handle graciously the error instead of using "die"

I think you need this:
function insert($file_path) {
foreach ($file_path as $file) {
//Your code here
}
}

Related

individual checkbox for each task returned in a ajax call [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a question about checkboxes. I am making a website that lets users enter their tasks for the day and can check the tasks off once they are complete. They can browse the tasks by selecting the date. I am using the AJAX get method to get the tasks from the database and display them in the webpage. I am not sure how to create a checkbox for each task I get from the AJAX method as I will be getting all the tasks for the selected date through one ajax call to the php script that connects to database and returns the tasks. And also how to identify which checkbox corresponds to which task.
In the db there are index numbers, task, date of the task, completed or not and the username
Any help will be greatly appreciated. Thanks
Make a JSON response from your PHP function that is returned with the ajax request and use the response to put the html in your page body.
For example, let's say you have the following PHP code:
<?php
$response = array();
$tasks = array(0 => "Task1", 1 => "Task1", 2 =>
"Task1");
$response['tasks'] = $tasks;
$html = '';
foreach($tasks AS $k => $v) {
$html .= '<input type="checkbox" id="task_' .$v. '" />';
}
$response['html'] = $html;
echo json_encode($response); ?>
?>
And once your AJAX request finoshes, you can put the checkboxes in your page with jQuery(?)
<script type="text/javascript">
yourAjaxFunxtinHere().success(function()
{
$('#container').html(response.html);
});
</script>

update PHP variable on click of html class [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to run PHP, specifically PHP I can't do it any other language, on click of a link with the class .URL
Specifically the PHP I need to run is this:
$list[4]+=10;
and the link that I need it to run on click of looks like this:
Some site's URL
I have heard about jQuery's ajax() function and its derivatives. But how can I do those to update the value of a PHP variable on click on .URL ?
First things first, most of your question is not possible in the way you want it done. Specifically incrementing a variable in PHP such that you have $list[4] += 10. I say this because when this script is run this won't exist anymore, you'd have to load it in from where ever you happen to be storing data (assuming a DB).
So, a short example of what you're trying to achieve you'll need a couple of files.
index.php - This is where your code happens that renders the page with the links on it.
link_clicked.php - This is called when a link is clicked.
You'll add need this basic Javascript in your code (it uses jQuery because you mentioned it in your question). I've broken this snippet into many pieces which is not how you'd normally write or see jQuery written to explain what is going on.
$(function() {
// Select all elements on the page that have 'URL' class.
var urls = $(".URL");
// Tell the elements to perform this action when they are clicked.
urls.click(function() {
// Wrap the current element with jQuery.
var $this = $(this);
// Fetch the 'href' attribute of the current link
var url = $this.attr("href");
// Make an AJAX POST request to the URL '/link_clicked.php' and we're passing
// the href of the clicked link back.
$.post("/link_clicked.php", {url: url}, function(response) {
if (!response.success)
alert("Failed to log link click.");
});
});
});
Now, what should our PHP look like to handle this?
<?php
// Tell the requesting client we're responding with JSON
header("Content-Type: application/json");
// If the URL was not passed back then fail.
if (!isset($_REQUEST["url"]))
die('{"success": false}');
$url = $_REQUEST["url"];
// Assume $dbHost, $dbUser, $dbPass, and $dbDefault is defined
// elsewhere. And open an connection to a MySQL database using mysqli
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbDefault);
// Escape url for security
$url = conn->real_escape_string($url);
// Try to update the click count in the database, if this returns a
// falsy value then we assume the query failed.
if ($conn->query("UPDATE `link_clicks` SET `clicks` = `clicks` + 1 WHERE url = '$url';"))
echo '{"success": true}';
else
echo '{"success": false}';
// Close the connection.
$conn->close();
// end link_clicked.php
This example is simplistic in nature and uses some unrecommended methods for performing tasks. I'll leave finding how to go about doing this properly per your requirements up to you.

How to get latest Tweets of an User [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am trying to get my client latest tweets. After Searching in Google i got some code. Unfortunately the code is working in localhost, But not working in the Hosting server. Its saying couldn't find the server. I am posting the code snapshot..
<?php
function getTwitterStatus($userid){
$url = "http://twitter.com/statuses/user_timeline/$userid.xml?count=1";
$xml = simplexml_load_file($url) or die("could not connect");
foreach($xml->status as $status){
$text = $status->text;
}
echo $text;
}
//my user id AmitEducation
getTwitterStatus("AmitEducation");
?>
Please help me out. If anyone have better suggestion please help me.
Use the Twitter Search API, it's really awesome. And it's JSON. [+1]
$tweets = json_decode(file_get_contents("http://search.twitter.com/search.json?q=php&rpp=5&include_entities=true&result_type=mixed"));
foreach($tweets->results as $t){
echo "Username: {$t->from_user_name}";
echo "Tweet: {$t->text}" . PHP_EOL;
}
Please read the documentation for how to use and see examples.
change the username in the link
<?php
$json = file_get_contents("http://twitter.com/status/user_timeline/username.json?count=10", true); //getting the file content
$decode = json_decode($json, true); //getting the file content as array
print_r($decode);
?>

How can I use PHP to automatically change the page if [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
...the conditions of an if statement are fulfilled?
I have some code to add data to a database if certain conditions are met, after the data is added I want the page to redirect to another page? How can I do this?
Use if-else condition. You can use header() of PHP .
if(/* Your conditions */){
// redirect if fulfilled
header("Location:nxtpage.php");
}else{
//some another operation you want
}
You shoul use header php function
<?php
//some conditions
header("Location: http://www.example.com/");
?>
try this code
$query ="insert into test values (1,'test')";
if(mysql_query($query) == true)
{
header('location:index.php');
exit();
}
else
{
echo " insert failed";
}
Try PHP Header:
header('Location: http://www.example.com/');

To understand session overwriting better with two session initiations [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How can you see the assigned value of the following SESSION variable?
I run the following after start_session()
$_SESSION['login']['email'] = "ntohuh";
I get after printing with print_r($_SESSION);
( [login] => Array ( [email] => )
This question is based on this thread.
The value shows up for me. This is what I did, if it helps:
# This empties $_SESSION
$_SESSION = array();
session_start();
$_SESSION['login']['email'] = "ntohuh";
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
Reply to this question.
Source of the problem
I found out that the problem was in my handle_login_session.php -file at the very beginning of my index.php. I had this there
The very beginning of my index.php in the file handle_login_session.php
if( $_SESSION['login']['logged_in'] == false ){
$random_number = rand(1,100000);
$session_id = session_id($random_number);
$_SESSION['login']['email'] = ''; // problem here
}
I did not think that this could be a problem when making this because I have the following at the very end of my file
The end of my index.php in the file handle_registration.php
$email = $_POST['login']['email'];
$_SESSION['login']['email'] = "ntohuh"; // not effective
I had the idea that the code later in my index.php will overwrite the code before it. However, this is not the case here.
Explanation for the problem
I have one explanation for the strange behaviour.
The latter file is called by the following form in my index.php.
<?php
echo ("<form method='post'"
. "action='/codes/handlers/handle_registration.php" // called here
. "'>"
);
?>
<p>Email:
<input name="login[email]" type="text" cols="92" />
</p>
<input type="submit" value="OK" />
</form>
This action seems to make like an external environment which does not overwrite anything in the main environment.
The following picture summarizes the situation where the order of the files being called is shown.
handle_login_session.php ---- handler_registration ------
| |
index.php ----------------------------------------------------------------------->
time

Categories