php - get value from variable - php

I need to take value form variable, hode one part and send the other part in email.
This variable is sql anywhere query result.
This is what i have so far:
$res=sqlanywhere_query(...)
$resID=explode('#',$res);
$email.=$email_footer.$resID[1].$email_footer2;
When I had in email $res, in email I get something liike Resource #163.
When I put $resID[1], in place where should be 163, space was empty.

That is because your $res is a resource, you have to get the results.
You should have for that library something like
$sql = sqlanywhere_query(...)
$res = sqlanywhere_fetch($sql);
and $res will be an array with your query result;

It's a resource, which means that it's a special variable that holds a reference to an external source.
See the PHP manual on Resources.

please, using database with php. when you query, you must pass the result to a fetch function before you can access the values.
$res=sqlanywhere_query(...)
//fetch one
$data = sqlanywhere_fetch_row($res)
// or u loop through
while($row = sqlanywhere_fetch_row($res))
{
echo $row["id"];
}
all these functiosn are deprecated. you can use mysql_query and mysql_fetch_row (or other fetch functions).
you can also use mysqli_ functions. read PHP manual.
hope it helps

Related

PHP SQL result as whole "object"

I am working on project, which will have limited PHP processes and possibly, many people will use the page. So I am trying to optimize it so the most (but secure) things will be handled clientside.
$result = mysqli_query($db, "SELECT * FROM userdata");
/*return $result; */
while ($row = mysql_fetch_array($result)) {
//do sth, e.g. get row to array
}
/*return $array;*/
My question is simple in this case.
Looping through each line takes time and will block the php process for quite a time.
So, is here some solution, taht you will simply send SQL requests, from DB server you will get response in shape of "some bunch of data", that I will be able to pass directly to jquery, where I can handle/sort/edit/make viewable the result using client resoruces and not server resources?
(so far, making sql request and passing $result to jquery variable seems not returning anything, the jquery variable is empty)
Thanks in advance
First of all, it looks like you are mixing mysql with mysqli.
mysqli method:
mysqli_query($db, "SELECT * FROM userdata");
mysql method:
mysql_fetch_array($result)
You SHOULD NOT do this. mysql method is deprecated, and both method are different api entirely, they are not meant to work together, eventhought its work, it is plain wrong to do so.
As for you question, in order to pass the fetched db data result to jQuery or Javascript for client side processing, you can convert the result array to JSON strings.
Do like this:
$row = mysqli_fetch_array($result);
echo json_encode($row);
Then using jquery, make ajax call to the php script. and parse the json data.
I think you're asking for this function :
http://www.w3schools.com/php/func_mysqli_fetch_all.asp
which will retrieve ALL the rows into a single nested associative array. You can then encode this array using JSON_encode() to process using client-side javascript.

While loop is not working properly

I am having a while loop in my function for getting the values 1 by 1 but i am getting the only 1 value
while($row= mysqli_fetch_array($this->result))
{
$image=$this->getEventDetails($row['Album_top'],'Event_image');
$alert.="<div class=facBox>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>
<img src='admin/customer/eventgallery/$image' alt=''>
</a>
<div class=clear></div>
<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>$row[Album_title]</a>
</div>";
}
I am getting the image name from another function that is
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
$this->result=mysqli_query($this->con,$get);
$row=mysqli_fetch_array($this->result);
return $row[$fieldname];
}
Now i am getting the only value from the loop my $alert is having only one facbox. if i remove this line
$this->getEventDetails($row['Album_top'],'Event_image');
It works fine but i want this line to get the image name.
Inside getEventDetails(), you assign $this->result, overwriting the previous contents of $this->result. Since that occurs inside the while loop where the previous result is being used, the loop exits because there are no further results to retrieve from the inner fetch.
User a different temporary result set inside teh getEventDetails() method.
function getEventDetails($id,$fieldname)
{
$get="Select * from sarnaevent where Id='$id'";
// Different variable name...
$temporary_result = mysqli_query($this->con,$get);
$row=mysqli_fetch_array($temporary_result);
return $row[$fieldname];
}
In general, I would question the need to be storing a transient result resource into the object's $this->result for most purposes. In any case where you're using that inside a method, you are probably better off using a variable scoped only to the method, which lives only for the lifetime that result set is being used.
Please use caution when sending $id directly into the query. Although I suspect it is known to be an integer variable, and therefore it won't break the SQL, it's a good idea to get into the habit of using prepare()/execute() to prevent SQL injection.
One final point of caution: When placing the string variable into your HTML markup, be sure to use htmlspecialchars() to escape it against malforming the HTML. (If the Id is known to be an integer, it isn't necessary there)
"...<a href='gallery.php?id=$row[Id]' style=margin-top:0px;>" . htmlspecialchars($row['Album_title']) . "</a>..."
Instead of using mysqli_fetch_array() try using mysqli_fetch_assoc (see: http://php.net/manual/en/mysqli-result.fetch-assoc.php); the returned array will be associative (key-value pairs) where the keys are the column names.
You're blowing out your original query.
First, you do a query, and assign its result to $this->result. You then iterate across those results. For the first row, you immediately make a new query, overwrite $this->result with the new results, and then try to continue... but you've just replaced the rest of your results with the single result from the event details query, so mysqli_fetch_array doesn't find any more results.
Solution: use a separate variable for that result. A local one should be fine, since you don't use it outside that function. You may also need to use a separate connection; I'm not sure of that. Try it with just changing $this->result in getEventDetails() to use something like $eventResult instead.

What are the memory implications of passing a MySQLi result to a function in PHP?

Dear gods of Stackoverflow
Let's say I have a MySQL query that selects a large dataset:
$query = "SELECT col_1, col_2, ..., col_99 FROM big_table";
And I get a MySQLi result like so:
$result = $db->query($query);
But then instead of dealing with $result in this scope, I pass it to a function:
my_function($result);
And once inside my_function(), I iterate through each row in the result and do stuff:
function my_function($result) {
while($row = $result->fetch_object()) {
...
}
}
Please help me understand the memory implications of this approach.
In other words, what does $result contain, and are there any pitfalls with passing it to a function? Should I consider passing $result by reference instead? For what it's worth, I won't be needing $result once my_function() is done with it.
Cheers from South Africa!
You will not have any memory implications at all. $result holds a resource. It does not hold the whole result. It's just a resource Id of the result. MySQL uses this I'd to collect the result.
There are virtually no memory implications to this approach. PHP passes objects by reference, so very little memory is used when passing an object to a function.
The same is not quite true of arrays, they use a technique called Copy On Write, meaning that if you change an array inside a function then the array will be cloned.
You can always see for yourself what the impact is.
Objects in PHP 5+ are automatically passed by reference, so passing the result object into a function won't duplicate it.
You can then unset the variable after the function has been called.

An imported array from mysql works, but the array can't be used by php as an array?

The code below won't work because of this line $params=array($data);. It needs something other than $data. Or it needs something to happen with $data prior to this line.
If the line is written as $params=array("A", "B", "C", "D"); then it works great, but my array is in the $data variable, not written out like that. If there is a way to get the array converted to being written out like that, that would work too.
The end result should show every possible combination (not permutation) of the contents of the array. Like in the example above it shows ABC, BD, etc.
$data = mysql_query('SELECT weight FROM my_table WHERE session_id = "' . session_id() . '"');
$params=array($data);
$combinations=getCombinations($params);
function getCombinations($array)
{
$length=sizeof($array);
$combocount=pow(2,$length);
for ($i=1; $i<$combocount; $i++)
{
$binary = str_pad(decbin($i), $length, "0", STR_PAD_LEFT);
$combination='';
for($j=0;$j<$length;$j++)
{
if($binary[$j]=="1")
$combination.=$array[$j];
}
$combinationsarray[]=$combination;
echo $combination."<br>";
}
return $combinationsarray;
}
mysql_query() only returns a result resource ID. To retrieve data, you must use one of the "fetch" commands, for example
$params = array();
while ($row = mysql_fetch_assoc($data)) {
$params[] = $row['weight'];
}
Also, your query is possibly vulnerable to SQL injection. I wouldn't implicitly trust the value from session_id(). I'm not entirely sure of this but it may simply retrieve the value from the session cookie.
At the very least, sanitise the value with mysql_real_escape_string(). A more robust solution which would bring your code out of the dark ages would be to use PDO and parameter binding.
$data is not an array. Assuming mysql_query() did not return an error or an empty result (both of which you should check for, by the way--lookup documentation for mysql_error() and mysql_num_rows() perhaps, maybe some others), $data is a resource.
So you want $params=mysql_fetch_array($data) to make it an array. (That assumes that there is only one result. If it might return more than one row, you'll probably want to wrap it in a loop. If you are 100% certain that session_id is unique , then you can get away without the loop, I suppose. You can also get away without the loop if you only care about the first result in a multi-row result, although I'd throw in a LIMIT 1 in your query in that case to improve performance.)
There are lots of options (do you want a numerically indexed array, or one where they keys are the names of the columns, etc.) so read up at http://www.php.net/manual/en/function.mysql-fetch-array.php.
Ok there are alot of fundamental problems with your script. I personally recommend to first read this article and then about the actual function called mysql_fetch_array().
Simply put, what you are receiving from mysql is resource (corrent me if i'm wrong!) and you have to fetch array on that.
$params = mysql_fetch_array($data);
PS: This makes no sense: $params=array($data);

Print an SQL Query in PHP so it is 'human readable'

Is there a way of printing a result from an sql query rather than just reading a resource id? Something like the way 'print_r' works?
(Assuming MySQL.)
There is no native PHP functionality to iterate a resultset through a resource handle, no. You must iterate yourself using mysql_fetch_assoc.
On the upside, you can write a function to do it.
function print_rs($recordset) {
while ($row = $recordset->fetch_assoc())
print_r($row);
}
print_rs($db->query("SELECT * FROM `lol`"));
.. or something along these lines.
Are you printing the return value of mysql_connect? You should be looking in the output of mysql_fetch_assoc instead.

Categories