php mysql query in function not working - php

I have a mysql query that returns sum of values in multiple columns. The query is right and everything is working normally when i include it in the main page. But the problem starts when i make a function in another
page include the query over there and return the sum and print it in main page its not working .
Below is the main page call :
require('totals.php');
$res_easyhint_total=easyhint_totals($currentpid);
print $res_easyhint_total;
//The above is contained in a while loop and current pid gets updated each time.
Function page:
function easyhint_totals($currentpid){
require('connect.php');
$sql_easyhint_total = "SELECT sum(Coffee+Gift+Cools+Affection+Patience+Anger+EHignore) from whyangry.posts where Pid=$currentpid";
$res_easyhint_total=mysql_query($sql_easyhint_total,$con);
$res_easyhint_total=mysql_fetch_array($res_easyhint_total);
$res_easyhint_total=$res_easyhint_total[0];
return $res_easyhint_total;
}
I dont get what the error is please help.

Do you define any functions in connect.php? If not try adding this:
$res_easyhint_total=mysql_query($sql_easyhint_total,$con);
if (mysql_errno() != 0) {
echo mysql_error();
}
$res_easyhint_total=mysql_fetch_array($res_easyhint_total);

Have you checked the result from the new page there itself? I mean to say if you tried to print the result from the new page itself as like you tried from main page. Then one more thing need to concetrate that, the path of both file while including. Try to pass any other variable from the new page to main page and check if the new file included properly.
If you are able to access other variable from new page on main page and its just not returning the result from the function. Try to include connect.php on main page also and check it.

Check your connection string is returning the proper linked identifier and also check the logs if there is any error or warning from mysql like Warning: mysql_query(): [2002] No such file or directory (trying to connect via unix:///var/run/mysql/mysql.sock). In that case try to set the proper socket file location.

Have you included the file "connect.php" before?
if(!#include_once('connect.php')) {
// include connect.php
}

Related

Is it possible to output certain content on a php document and make it die only if it’s URL is present with a value of true on a MySQL database?

I am trying to setup a PHP document but I currently am looking for a way to use the die() function and display some content on every page using my global configuration file. The way I am think how it should work is that IF the requested URL (e.g. domain.com/services/disabledservice) would have /services/disabled service and a value of 1 to make the value true in a MYSQL DB.
The plan is to have the URL be collected and checked with a table than if the row has a value of 1 for status it will display a disabled page message but if it’s 0 it will load normally.
Some research I have conducted may lead be to think that using the SQL query and the if function could work for this.
The idea I have is this but it may not be correct.
<?php $pageurl = [requested URL content here]
$checkstatus = "SELECT * FROM servicestatus WHERE page =" . $pageurl . "AND status = 1";
if ($status = mysqli_query($conn, $servicestatus)) {
if (mysqli_num_rows($status) = 1) { ?> html content here
<?php }
} else { ?>
page as normal
<?php } ?>
Edit:
To explain what I am trying to do.. I am trying to fetch the URL without everything past “?” Than I am trying to use that in a DB query to check with the database if that has a value of “m” or “d” and if it has one of those values next to the URL which is being fetched it will display the appropriate error page. This is being included as part of my core configuration file which includes my “$conn” and the core values for most stuff. The problem I am facing is that when I send my URL without everything past the “?” I am not receiving my error page and everything is loading like normal.
Use any one the following php functions:
include 'path_to_the_page.php' (or) require 'path_to_the_page.php';
The difference between include and require arises when the file being included cannot be found: include will emit a warning ( E_WARNING ) and the script will continue, whereas require will emit a fatal error ( E_COMPILE_ERROR ) and halt the script.

php querying for data just inserted...by itself

I don't know how to title this...but anyway,
In my script if data doesn't exist, i insert a new row into a database and then check again for that row, for example:
1 search the db
2 if nothing
include(create.php) -> create entry
3 search the db for that row
Am I going to have to put in a usleep(1000000); between the include and the next search on the db? or is there something I am missing?
THanks!
Include the file create.php on top of your php script and call the functions you required inside this block
if ($number_of_rows < 1) { //call the functions from create.php you need here}
Seriously, why even have a create.php used in that manner anyway? Include create.php at the top of the page, put all the insert syntax into a function, and call it later on in your main script. That would work.
Or even better, don't even bother including it. Just run the queries straight in your main page. That way if you need to change something, you won't have to affect other pages.
You can use something like that
$query="Select * from table where id='23'";
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
//result find in sql table
}else{
$query1="INSERT INTO table (schema) values(values)";
$result=mysql_query($query1);
}
sleep(1);
$query="select *...."
You can also use mysql INTERVAL query.It will automatic make a query after a particular interval and search for data.

Returning a resultset from one page to another in PHP

I have 2 php pages: query.php and result.php.
In query.php, I am executing a query (select) statement. It's returning a resultset
$rs = mysql_query($query);
Now I want to return this resultset from query.php to another page result.php and work with it. Like this:
In query.php:
return $rs
and in result.php:
$result = executeQuery($query) // we get the resultset in this variable
while ($row == mysql_fetch_array($result){
//do something
}
If the above is not recommended, please provide me with alternatives. But I want the query function and resultset in different pages.
You could just include results.php in your query.php page if you're just looking to keep the code separate in the source files but aren't actually required to redirect from one page to another:
In query.php:
$rs = mysql_query($query);
include "results.php";
In results.php:
while ($row == mysql_fetch_array($rs){
//do something
}
As far as trying to "return $rs" from one page to another that's not how PHP works. The return statement is only valid within a function. If you want to actually pass data from one PHP page to another and will be redirecting to that other page then you'll need to use either a session, a cookie, pass it in the URL (i.e. use GET) or use curl and add it as a POST var.
If this is really the way it must be, store the result set in a database somewhere or in a file and give each result a unique name. Then pass that name to the next page so it can be retrieved.
query.php will redirect to result.php?result_set=ab24sdfsdfklls for instance.
This has the added advantage that you can use the result_set as often as you want. Visitors can have multiple result sets during one visit. They can share the URL of the result set page with other people, etc.
Just be sure to eventually prune the data store as it will just keep on growing, but that's another matter entirely.

PHP undefined index error when clicking a url and invoking a php script

I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}

Echo SQL query on new page with PHP

I know this is probably a really amateur question, but I can't figure this out and I don't know much about PHP or MySQL.
So I have a really simple script that basically allows a user to submit a couple lines of text and their zipcode, then it write it to a database and returns the results on the site. It's a shoutbox essentially.
My client wants the users to be able to filter the results by zipcode. So I have it all setup, and I have a search input where people type in their zipcode, search, and then the PHP returns the submissions from that zipcode.
While I can get the results to show by themselves echoed from the PHP script, how do I get them to display within a specified div within the site? I want it essentially to store a variable, the zipcode, that a user search by, and then use that once the page refreshes to display an updated list that filters out the results that aren't from that zipcode.
Thanks so much for the help.
Chris
Without getting into rewriting etc.:
When you redirect your page, add a query at the end of it that is the zipcode making sure that you don't send any whitespace and that you have an input in a given format:
search.php?zipcode=90210
Then on your search results page, fetch the variable passed and work as usual:
$zipcode = $_GET['zipcode'];
make sure that the zipcode is properly escaped and filtered for nasties.
Make the HTML page a PHP page (usually by making the extension .php). Replace the target div's content with <?php stuff to get and print results ?>.
If you have PHP installed and configured on the web server, it will take certain files (usually those ending in .php) and run them through PHP's interpreter. The PHP interpreter is invoked anytime there is a <?php in the document and it stops parsing content anytime it meets a ?> within the <?php block.
For instance, to get a web page to print "Hello World!" into a div through PHP, I would do:
<div><?php
print 'Hello World!';
?></div>
OK, I figured it out. I just stored my answer in a SESSION variable so that I could call it in my other PHP files.
Now I have one file processing the request, creating the session and the variable, and then redirecting the page. Then I have a PHP included in the page that grabs the SESSION variable and plugs it into my mysql_query to return the proper result!
Not sure if this is the best way of doing it, but it's working.... If anyone knows of a more elegant solution I would love to know it.
Thanks,
Chris
I suggest you do some tutorials on using PHP and database retrieval with mysqli.
<?php
/* Connect to a MySQL server */
$link = mysqli_connect(
'localhost', /* The host to connect to */
'user', /* The user to connect as */
'password', /* The password to use */
'world'); /* The default database to query */
if (!$link) {
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
/* Send a query to the server */
if ($result = mysqli_query($link, 'SELECT Name, Population FROM City ORDER BY Population DESC LIMIT 5')) {
print("Very large cities are:\n");
/* Fetch the results of the query */
while( $row = mysqli_fetch_assoc($result) ){
printf("%s (%s)\n", $row['Name'], $row['Population']);
}
/* Destroy the result set and free the memory used for it */
mysqli_free_result($result);
}
/* Close the connection */
mysqli_close($link);
?>

Categories