A Sql function with PHP - php

I'm making a basic function for adding logs on admin pages. (Please ignore the values).
$sql = "INSERT INTO logs(query,userid,time,page) VALUES('$query',$userid,NOW(),'$pagename')");
I'm just attempting to have it in a function like this
function myfunctionforlogs(){
$sql = "INSERT INTO logs(query,userid,time,page) VALUES('$query',$userid,NOW(),'$pagename')");
}
In other pages, I'm hoping to call it as
myfunctionforlogs();
What should I do? And thanks!
Sorry all for the misunderstanding. I have about 10 admin pages and I have a table to record logs. The standard query is what I have posted above. Now, I don't want have that code in every single page, so I have a file named "func.php". I'm hoping I can have that query in a function, so I can just call the function when I want to in other files.

your question is really hard to understand, but maybe you want this?
function myfunctionforlogs($query, $userid, $pagename){
$sql = "INSERT INTO logs(query,userid,time,page) VALUES('$query',$userid,NOW(),'$pagename')");
execute_sql($sql); //<-- another function, that actually runs the sql against the DB
}
now you can call your function anywhere you want to log the script:
myfunctionforlogs('select * from test', 'jimmy', 'index.php');
Btw. CamelCase is a much more readable format for function-names and identifiers in general.

Related

Is there a way to make a variable created within an isset($_GET[]) condition be accessed inside an isset($_POST[]) condition?

I have been stuck on this following problem for the past few days which I cannot seem to resolve.
I have the following two if statements within a PHP file:
This statement gets the post ID from the previous page.
if(isset($_GET['post'])){
$post_id = $_GET['post'];
}
This statement inserts user inputs into a DB_Table after a button is clicked. Amongst the data inserted into the DB_Table, I want the $post_id from the (isset($_GET['post'])) condition to be one of them.
if(isset($_POST['submit'])){
$insert_member = "insert into hcg_members (post_id, member_id) values ('$post_id','$match_member_id')";
$run_event = mysqli_query($con,$insert_member);
}
Only problem is, I can't seem to find a way to retain the $post_id's data. I have tried to set $post_id as a $Globals variable but this does not work.
As a way to find troubleshoot the problem I have successfully echoed $post_id from outside the if(isset($_GET[])) statement but the echo statement stops working once I try to run it from the if(isset($_POST[])) statement.
Any help would be appreciated, thanks in advance.
This code produces the below query when for example $_GET['post'] = 5, which looks fine to me. Could you elaborate on what goes wrong? Does this code somehow resides in different functions, so it could be a case of variables not being accessible?
insert into hcg_members (post_id, member_id) values ('5','')
Okay, so just to clarify for those who found my question unclear. I was trying to make 2 different calls to my script.
The first one was a GET request.
The second one was a POST request.
I was trying to do the above while retaining the value of $post_id which was located in the GET request when using it in the POST request.
As advised by dan08 & Crayon Violent, variables' values cannot be retained when trying to pass them from one HTTP request method to another. As pointed out by Crayon Violent, http is a stateless protocol, which makes PHP unable to remember anything from the previous request.
I therefore used one of Crayon Violent's solution which was to use session in order to carry over the variable from the Get Request method to the POST Request method, and it worked! :)
There's the solution:
GET Request Method:
<?php
#session_start();
if(isset($_GET['post'])){
$post_id = $_GET['post'];
$_SESSION['respite_id'] = $post_id;
}
...
...
?>
POST Request Method:
<?php
include("includes/database.php");
if(isset($_POST['submit'])){
$respite_id = $_SESSION['respite_id'];
$insert_member = "insert into hcg_members (post_id, member_id) values ('$post_id','$match_member_id')";
$run_event = mysqli_query($con,$insert_member);
...
...
}
?>
Thanks again to dan08 and Crayon Violent's support! :)

mysql_query update with indeterminate number of parameters

I have an update.php file, calling a function which is on "functions.php" in order to update info.
I would like to know if there is a way to make a unique function for Updating, which would work independently on the number of arguments needed for it.
I know one way of doing this, which is, on the php file, saving the entire query on a variale first and then sending it to functions.php with the variable as parameter, as seen on here:
PHP file:
$queryUpdate="UPDATE carta SET titulo='$titulo', ingredientes='$ingredientes', precio='$precio', tipo='$tipo', porcentaje='$porcentaje', imagen='$rutaFinal' WHERE id_carta='$id'";
$update = consultaQuery($queryUpdate);
FUNCTIONS file:
function consultaQuery($par_query){
$consulta = mysql_query($par_query);
return $consulta;}
But I was wondering if there is another way of dinamizing my function to send any $variables=values separately in order to be added to a mysql_query(UPDATE) query.
I could do this by:
PHP file:
$update = consultaQuery($titulo,$ingredientes,$precio,$tipo,$porcentaje,$rutaFinal,$id);
FUNCTIONS file:
function consultaQuery($par_titulo,$par_ingredientes,$par_precio,$par_tipo,$par_porcentaje,$par_rutaFinal,$par_id){
$consulta = mysql_query(UPDATE carta SET titulo=$par_titulo, ingredientes=$par_ingredientes, precio=$par_precio, tipo=$par_tipo, porcentaje=$par_porcentaje, imagen=$par_rutaFinal WHERE id_carta='par_id);
return $consulta;}
But this would not work, for example, with a 3-argument update. Is there any way of making this? Do I keep doing this as the first way? Thank you for your attention.

How to view how many MySQL queries ran on page load

I'm testing performance on a CMS I'm making, and I'm wondering is it possible to view what queries were ran on a page load. For example, let's say I run 'test.php'. When I go to it, a list of queries ran by mySQL show at the bottom of the page - is this possible? I've seen sites do this before.
Thanks
The function SHOW FULL PROCESSLIST will show the real-time and past history of all processes.
SHOW FULL PROCESSLIST
If you are using a server on which you have the rights to install packages, you can install mysqltop and test in real time file and MySQL resource usage and queries.
Well, if all your queries go through a function then it should be easy, but if each only uses the standard call, then it won't be. This also let's you switch to a different database type or something like that easily.
For instance on the CMS's I modified to be a library program, I have a DB Query function:
function db_query($qstring, $conn) {
$dbh = mysql_db_query($dbname,$qstring, $conn);
// this is where I would add some incrementing code, but it has to be global.
// or just do something like
if($_GET["debug"]=="debuginSQLcount"){
echo $qstring
}
return $dbh;
}
then to use it, I just do something like
$sql = "SELECT stuff";
}
$result = db_query($sql, $link);
if (!$result || db_numrows($result) < 1) {
If you do it like this, then just add a line to the function which increments a $GLOBALS variable or something like that. Read more at PHP global or $GLOBALS

Joomla! no result on query

I have a basic query in Joomla! and I really, really can't figure out why it doesn't return anything:
$database =& JFactory::getDBO();
$query = "SELECT * FROM my_table";
$database->setQuery($query);
$result = $database->loadObjectList();
var_dump($result);
die();
Query is very, very basic, I know.
It returns $result as null. Thing is, I run this query in a separate .php scrip file (localhost/myscript.php). All other queries in the rest of my website seem to run just fine (including some in other script files like this one).
I've run this query in a terminal and returns what I want. Please, I need some idea :)
If your trying this in a separate php file (localhost/myscipt.php) as you say, you need the proper classes. See this post. The last answer has some details.
However this is not recommended. You should be using module or plugin development all within the framework.
Alternatively, you could use Jumi which allows you to write any code you want and include it as part of a module. Makes life a lot easier.
I think your query is missing a table prefix, you can echo the prefix using $database->getPrefix();
also try changing
$query = "SELECT * FROM my_table";
to
$query = "SELECT * FROM `#__my_table`";
NOTE: Joomla uses a placeholder for the prefix, the “#__” will be replaced with the correct prefix.

mysql data being inserted twice via php

I can't for the life of me figure out why this function is causing multiple entries into my database table...
When I run the function I end up with two records stacked on top of each one second apart
screen cap http://img132.imageshack.us/img132/5053/screenshot20100517at259.png
here is the function:
function generate_signup_token(){
$connection = new DB_Connect(); // <--- my database connection class
$ip = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$sign_up_token = uniqid(mt_rand(), true);
$_SESSION['signup_token'] = $sign_up_token;
$sign_up_token = mysql_real_escape_string($sign_up_token);
$query = "INSERT INTO `token_manager` (`ip_address`, `signup_token`) VALUES ('$ip', '$sign_up_token')";
mysql_query($query);
}
generate_signup_token();
The biggest piece of evidence that this function is being called more than once is the different signup tokens that are being generated.
Also, there is a one second difference between inserts which may be indicative of multiple page requests. If there is consistently such a time disparity, I'd investigate the access log. If there's only one page request, then the function must be called more than once somehow.
It looks like your function is fine. It appears that you are somehow calling the function twice. I'd suggest adding some debugging information to the function to figure out why. The function debug_print_backtrace might come in handy for this.

Categories