Passing dynamic parameters into a function - php

Suppose i have a function called ssh_connect that takes a server SSH settings as parameters.Now i have multiple servers and i want to choose one of them randomly and input them as parameters into the function.Moreover if $result is empty when using one set of parameters , the other set must be used
$result=ssh_connect($ip, $user, $pass, $port,$command)
Suppose i have the following details
//Server 1
$ip="123.456.78.901";
$user="root"
$pass="mypassishere"
$port = "22"
//Server 2
$ip="225.456.98.901"
$user="root"
$pass="mypassishere"
$port = "22"
I could use selection structures but that solution is heavily flawed as one server will always have priority over the others.It will be like if $result is empty with Server 1 details , move to server 2 , which is really not what i want.
I am thinking of array but i am not sure how it will be done since i need to select a set of details randomly and if one set fails try another one until there are no servers or $result has got a value.

Continued from #gwillie 's answer, here is an example:
<?php
$a = array(
array('host'=>'host1','user'=>'user1','pwd'=>'pwd1'),
array('host'=>'host2','user'=>'user2','pwd'=>'pwd2'),
array('host'=>'host3','user'=>'user3','pwd'=>'pwd3'),
array('host'=>'host4','user'=>'user4','pwd'=>'pwd4'),
array('host'=>'host5','user'=>'user5','pwd'=>'pwd5'),
);
$connect = false;
while (!$connect) {
$srvIndex = array_rand($a);
$host = $a[$srvIndex];
$connect = my_connect_function($host); //Return true on success, false on error
}

I think you are looking for aray_rand, php site states
Picks one or more random entries out of an array,
and returns the key (or keys) of the random entries.
If settings fail, unset the key returned by array_rand(), keep looping till you connect, or fail

Related

Why search query not showing any result in PHRETS?

I am using this php script to get the result from a simple search query documented here
And I have downloaded this excel file of metadata of property here
$rets_login_url = "http://sef.rets.interealty.com/Login.asmx/Login";
$rets_username = "xxxxxxxx";
$rets_password = "xxxxxxxx";
$rets_user_agent = "PHRETS/1.0";
$rets_user_agent_password = "xxxxxxx";
//////////////////////////////
// start rets connection
$rets = new phRETS;
// Uncomment and change the following if you're connecting
// to a server that supports a version other than RETS 1.5
$rets->AddHeader("RETS-Version", "RETS/1.5");
$rets->AddHeader("User-Agent", $rets_user_agent);
echo "+ Connecting to {$rets_login_url} as {$rets_username}<br>\n";
$connect = $rets->Connect($rets_login_url, $rets_username, $rets_password, $rets_user_agent_password);
// check for errors
if ($connect) {
echo " + Connected<br>\n";
}
else {
echo " + Not connected:<br>\n";
print_r($rets->Error());
exit;
}
$search = $rets->SearchQuery("Property","ResidentialProperty","(ListDate=1990-01-01+)");
while ($listing = $rets->FetchRow($search)) {
echo "Address: {$listing['StreetNumber']} {$listing['StreetName']}, ";
echo "{$listing['City']}, ";
echo "{$listing['State']} {$listing['ZipCode']} listed for ";
echo "\$".number_format($listing['ListPrice'])."\n";
}
$rets->FreeResult($search);
echo "+ Disconnecting<br>\n";
$rets->Disconnect();
when I run this script it shows the result connected and then disconnected. But no result is found. I tried many things suggested on some questions for which result was not showing, But nothing is working for me. Where I am wrong?
My RETS server information are here:
RETS Server: SEF RETS System
RETS System ID: SEFRETS
Login URL: http://sef.rets.interealty.com:80/Login.asmx/Login
RETS Version: 1.5
Server Software: Microsoft-IIS/6.0
I also could not understand what is $rets_modtimestamp_field = "LIST_87";
Please Help me. I need some suggestion over how to get data from the RETS.
The issue is with the parameters in your SearchQuery.
One of the fields in your search query is ListDate. Looking at the attached excel file containing the metadata, "ListDate" is in Column B under StandardNames. The RETS specification uses System Names as default (see below). You need to specify '"StandardNames" => 1' in the options parameter in the SearchQuery function:
$search = $rets->SearchQuery("Property","ResidentialProperty","(ListDate=1990-01-01+)",array("StandardNames" => 1));
Also, check to make sure the second argument, class, of your SearchQuery is correct. To do this you could use the GetMetadataClasses function in PHRETS.
You could also use retsmd.com by logging in with your RETS Server url, username, and password.
The $rets_modtimestamp_field is the field which is a datetime value indicating the date and time when a listing was last modified.
In section 7.4.7 in the RETS 1.7.2 Specification document, http://www.reso.org/assets/RETS/Specifications/rets_1_7_2.pdf,
"Queries may use either standard names or system names in the query (Section 7.7). If the
client chooses to use standard names, it MUST indicate this using the StandardNames
argument...If this entry is set to ("0") or is not present the field names passed in the search are the
SystemNames, as defined in the metadata."
To address your last comment, you need to specify ListingStatus as well, as it is also a required field when running a query. The lookup values for ListingStatus are:
A = Active-Available
B = Backup Contract-Call LA
C = Cancelled
CS = Closed Sale
PS = Pending Sale/Rental
Q = Terminated
T = Temp Off Market
W = Withdrawn
X = Expired
So try something like this instead:
$query ="(922=MIAMI),(246=A)";
Or if you're using standard names:
$query ="(City=MIAMI),(ListingStatus=A)";
And finally:
$search = $rets->SearchQuery("Property", $class, $query, array("StandardNames" => 1, 'Limit' => 10, ));
This should allow you to get some results back at least. Beyond that you can just tweak your query until you get the results you want.

Getting users data from same field

So, I'm writing an application in PHP and I'm trying to retrieve unique user data based on what they entered. Here is my code:
function hello($username123) {
// Connect to Database //
$host3 = "db";
$username3 = "db";
$password3 = "db";
$db3 = "db";
$con3 = mysqli_connect($host3,$username3,$password3,$db3) or die("Can not connect to Server.");
$student1name;
$query3 = mysqli_query($con3,"SELECT * FROM 'users' WHERE 'username' = '$username123' and '$student1name' = 'student1'");
return "$student1name";
}
So, the user enters there username which they registered earlier on and then I run a query where the username field is equal to the username variable (The input) and that the student1name variable is equal to the student1 field where the username is the same as the one entered. I then return the student1name variable. But when I test this all that returns is "". I can't figure out the problem
You must bind the result in a result array and access it like that, something like this should work:
return $query3["student1name"];
Would probably be more effective.
If you're only selecting ONE variable in your query then you can simply echo $query3.
It would also be more effective if you'd look into prepared statements.
Note that
$student1name
doesn't do anything since you never give it a proper value.
you are not fetching the results of the query, try something like this after your query..
$row = mysqli_fetch_array($query3, MYSQLI_ASSOC);
return $row['studentname'];
i'm assuming the student's name is in a column called studentname in your DB
PHP automatically replaces any variables you use inside a string to the value of that variable. For example, if $student1name = 'foo' then putting $student1name anywhere in your SELECT statement literally outputs you a string 'foo' in place of that variable. As far as the mysqli statement is concerned, you aren't using a PHP value, you are using a literal string 'foo'. Therefore, expecting your $student1name var to magically change based on the sql statement isn't going to happen.
To retrieve a column's value you will need to fetch the result rows after you perform the query:
if ($row = $query3->fetch_assoc()) {
return $row["student1"];
}
If you are expecting more than one result row, then you just need to call fetch_assoc() again for each row until it returns you nothing (marking the end of the result rows).

Building interactive WHERE clause for Postgresql queries from PHP

I'm using Postgresql 9.2 and PHP 5.5 on Linux. I have a database with "patient" records in it, and I'm displaying the records on a web page. That works fine, but now I need to add interactive filters so it will display only certain types of records depending on what filters the user engages, something like having 10 checkboxes from which I build an ad-hoc WHERE clause based off of that information and then rerun the query in realtime. I'm a bit unclear how to do that.
How would one approach this using PHP?
All you need to do is recieve all the data of your user's selected filters with $_POST or $_GET and then make a small function with a loop to concatenate everything the way your query needs it.
Something like this... IN THE CASE you have only ONE field in your DB to match with. It's a simple scenario and with more fields you'll need to make it so that you add the field you really need in each case, nothing too complex.
<?php
//recieve all the filters and save them in array
$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';
//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}
//at this point $filters has a string with all your
//Then make the connection and send the query. Notice how the select concatenates the $filters variable
$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$query = "SELECT * FROM table WHERE ".$filters;
$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");
while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";
//or whatever way you want to print it...
}
pg_close($con);
?>
The above code will get variables from a form that sent 3 variables (assuming all of them correspond to the SAME field in your DB, and makes a string to use as your WHERE clause.
If you have more than one field of your db to filter through, all you need to do is be careful on how you match the user input with your fields.
NOTE: I did not add it here for practical reasons... but please, please sanitize user input.. ALWAYS sanitize user input before using user controlled data in your queries.
Good luck.
Don't do string concatenation. Once you have the values just pass them to the constant query string:
$query = "
select a, b
from patient
where
($x is not null and x = $x)
or
('$y' != '' and y = '$y')
";
If the value was not informed by the user pass it as null or empty. In the above query the x = $x condition will be ignored if $x is null and the y = '$y' condition will be ignored if $y is empty.
With that said, a check box will always be either true or false. What is the exact problem you are facing?
Always sanitize the user input or use a driver to do it for you!
I have created a Where clause builder exactly for that purpose. It comes with the Pomm project but you can use it stand alone.
<?php
$where = Pomm\Query\Where::create("birthdate > ?", array($date->format('Y-m-d')))
->andWhere('gender = ?', array('M'));
$where2 = Pomm\Query\Where::createWhereIn('something_id', array(1, 15, 43, 104))
->orWhere($where);
$sql = sprintf("SELECT * FROM my_table WHERE %s", $where2);
$statement = $pdo->prepare($sql);
$statement->bind($where2->getValues());
$results = $statement->execute();
This way, your values are escaped and you can build dynamically your where clause. You will find more information in Pomm's documentation.

insert dummy data to mysql fast

I have 1 function in my debug model which i want to use in order to add dummy data to my app to test its speed and such...
the problem is that it needs to add records to 2 different tables and also check for duplicates usernames etc before each record is added to db so it takes a little time...
also this procedure is repeated about $total different dummy records i want to add at once in a for loop...
for example for 100 new users i want to add it takes around 5 seconds to proceed.
is this time fine or do i need to optimize it?
what if i want to add 1000,10000 users at once?? is it possible?
EDIT:
Function called to insert data:
public function registerRandomUsers($total = 1){
$this->load->model("misc_model");
$this->load->model("encryption_model");
$this->load->model("signup_model");
for ($i=1;$i<=$total;$i++){
$username = $this->misc_model->generateRandomString(15);
$flag = false;
while ($flag == false){
if ($this->user_model->usernameExist($username)){
$username = $this->misc_model->generateRandomString(15);
}else{
$flag = true;
$password = 'Test123';
$email = $username.'#email.com';
$data = array(
'username' => $username,
'password' => $password,
'email' => $email
);
$this->signup_model->submitRegistration($data);
$userdata = $this->user_model->getUserData($username, "username");
}
}
}
}
If you're not worried about having a random string as the user name, just set the $email = 'user'.$i.'#email.com'; (so you don't have to worry about collisions). The main reason this will be running slow is because you're sending a new query to the database on each iteration of the loop - it would be much much faster to generate a bulk insert string like:
INSERT INTO user (email,pass)
VALUES ('user1#email.com','Test123')
, ('user2#email.com','Test123')
, ('user3#email.com','Test123')
, ('user4#email.com','Test123')
, ('user5#email.com','Test123');
This way you can avoid the overhead of tcp traffic from sending 10000 queries to the database and have it do it all in one go.
I think if you're really looking for some realistic sample/test data, you should use generatedata.com.
http://www.generatedata.com/
It's one of the best I have seen so far.
Build your query as this
$conjuctions = str_repeat("('dummy#email.com','test pass'),", 20); // 20 dummy datas
$query = "INSERT INTO user (email,pass) VALUES ".substr($conjunctions,0,str_len($conjuctions).";"
// ^ This is to remove the last comma

Lots of 'If statement', or a redundant mysql query?

$url = mysql_real_escape_string($_POST['url']);
$shoutcast_url = mysql_real_escape_string($_POST['shoutcast_url']);
$site_name = mysql_real_escape_string($_POST['site_name']);
$site_subtitle = mysql_real_escape_string($_POST['site_subtitle']);
$email_suffix = mysql_real_escape_string($_POST['email_suffix']);
$logo_name = mysql_real_escape_string($_POST['logo_name']);
$twitter_username = mysql_real_escape_string($_POST['twitter_username']);
with all those options in a form, they are pre-filled in (by the database), however users can choose to change them, which updates the original database. Would it be better for me to update all the columns despite the chance that some of the rows have not been updated, or just do an if ($original_db_entry = $possible_new_entry) on each (which would be a query in itself)?
Thanks
I'd say it doesn't really matter either way - the size of the query you send to the server is hardly relevant here, and there is no "last updated" information for columns that would be updated unjustly, so...
By the way, what I like to do when working with such loads of data is create a temporary array.
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$$field = mysql_real_escape_string($_POST[$field]);
the only thing to be aware of here is that you have to be careful not to put variable names into $fields that would overwrite existing variables.
Update: Col. Shrapnel makes the correct and valid point that using variable variables is not a good practice. While I think it is perfectly acceptable to use variable variables within the scope of a function, it is indeed better not use them at all. The better way to sanitize all incoming fields and have them in a usable form would be:
$sanitized_data = array();
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$sanizited_data[$field] = mysql_real_escape_string($_POST[$field]);
this will leave you with an array you can work with:
$sanitized_data["url"] = ....
$sanitized_data["shoutcast_url"] = ....
Just run a single query that updates all columns:
UPDATE table SET col1='a', col2='b', col3='c' WHERE id = '5'
I would recommend that you execute the UPDATE with all column values. It'd be less costly than trying to confirm that the value is different than what's currently in the database. And that confirmation would be irrelevant anyway, because the values in the database could change instantly after you check them if someone else updates them.
If you issue an UPDATE against MySQL and the values are identical to values already in the database, the UPDATE will be a no-op. That is, MySQL reports zero rows affected.
MySQL knows not to do unnecessary work during an UPDATE.
If only one column changes, MySQL does need to do work. It only changes the columns that are different, but it still creates a new row version (assuming you're using InnoDB).
And of course there's some small amount of work necessary to actually send the UPDATE statement to the MySQL server so it can compare against the existing row. But typically this takes only hundredths of a millisecond on a modern server.
Yes, it's ok to update every field.
A simple function to produce SET statement:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
and usage:
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";

Categories