mysql_query update with indeterminate number of parameters - php

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.

Related

Codeigniter Commands out of sync; you can't run this command now

I've been spent hours trying to figure out how I'm supposed to get around this error in my scenario. I'm trying to run a few queries in sequence.
I have read: codeigniter : Commands out of sync; you can't run this command now, however I am not able to update /system/database/drivers/mysqli/mysqli_result.php
I've tried:
$this->db->reset_query();
$this->db->close();
$this->db->initialize();
$this->db->reconnect();
mysqli_next_result( $this->db->conn_id );
$query->free_result();
But they either give me the same error, or different errors which I will detail in the comments of my code.
The way my code is organized- I have a make_query method that takes a bunch of search options and figures out which tables to join and fields to search based on those. Sometimes, I just want to count results, sometimes I want all of the resulting data, sometimes I just want distinct values for certain fields or to group by certain fields. So I call make_query with my options, and then decide what to select afterwards. I have also been saving my query text to report, so that users can see what query is being run.
One interesting thing I have noted is that when I have no options set (ie there are no WHERE clauses in my SQL), I do not get this error and the multiple queries are able to run with no problem!
Here is my code:
//Get rows from tblPlots based on criteria set in options array
public function get_plot_data($options=array()){
$this->db->save_queries = TRUE;
log_message('debug','before make query 1 get plot data');
$this->make_query($options,'plot');
log_message('debug','after make query 1 get plot data');
$this->db->distinct();
//Now, set select to return only requested fields
if (!empty($options['fields']) and $options['fields']!="all" ){
//Because other tables could be joined, add table name to each select
array_walk($options['fields'], function(&$value, $key) { $value = 'tblPlots.'.$value;} );
$this->db->select($options['fields']);
}
if (!empty($options['limit']) and $options['limit']>0){
$this->db->limit($options['limit'], $options['offset']);
}
//Get the resulting data
$result=$this->db->get('tblProgram')->result();
$query_text = $this->db->last_query(); //tried removing this but didn't help
log_message('debug','query text '.$query_text);
$this->db->save_queries = FALSE;
//get the number of rows
//$this->db->reset_query();
//$this->db->close();
//$this->db->initialize();
//$this->db->reconnect();
//mysqli_next_result( $this->db->conn_id );
//$this->db->free_result(); //Call to undefined method CI_DB_mysqli_driver::free_result()
//$result->free_result(); //Call to a member function free_result() on array
log_message('debug','before make query 2');
$this->make_query($options,"plot");
$this->db->select('pkProgramID');
log_message('debug','before count results');
//this is where my code errors out trying to do the next step:
$count=$this->db->count_all_results('tblProgram');
}
I'm not including the code for make_query because it is long and calls other functions, but it runs successfully the first time and outputs the SQL query I would expect. If it would be helpful, I can include that code as well.
I'm not sure how to correctly call free_result() given that the CI documentation only gives an example using query('SQL QUERY') and I am building the query using Active Record, so I'm not sure how to use free result in my scenario? Maybe that's the issue?
$query2 = $this->db->query('SELECT name FROM some_table');
$query2->free_result();
Thank you for any help!
I ended up posting on a CI forum that suggested https://www.youtube.com/watch?v=yPiBhg6r5B0 which worked! Also I ended up having to join my tables differently to avoid timeouts (I think I was having trouble because I was using AJAX to call many queries asynchronously and one of them was timing out). Hope this helps someone!

Create a variable in one function and pass it to another in PHP

Let me first say I've spent a day reading three google pages of articles on this subject, as well as studied this page here.
Ok, here's my dilemma. I have two functions. Both called upon via AJAX. This first one assigns a value to the variable and the second one uses that variable. Both functions are triggered by two separate buttons and need to stay that way. The AJAX and the firing off of the functions work fine, but the variable isn't passed. Here is my code:
if( $_REQUEST["subjectLine"] ) //initiate first function
{
$CID = wpCreateChimpCampaign();
echo $CID; //this works
}
if( $_REQUEST["testEmails"] ) //initiate second function
{
echo $CID; //does not return anything but should contain "apple"
wpSendChimpTest($CID);
}
function wpCreateChimpCampaign () //first function
{
$CID = "apple";
return $CID;
}
function wpSendChimpTest ($CID) //second function
{
echo $CID; //does not return anything but should contain "apple"
}
I'm open to using a class but I haven't had much luck there either. I was hoping to solve this issue without using classes. Thanks for the help in advance!
If you are making 2 separate calls to this file, it may be helpful for you to visualise this as being 2 functions in 2 totally separate files. Although they exist in the same PHP file, because they used called in different calls, they don't retain the value of the variable $CID. Once the file has run, the variable is destroyed and when you call the file again, the value is null again.
So you need to store that variable between calls. You can either store it in a database or store it in a session variable.
So call session_start(); at the beginning of the file, then rather than use $CID, just use $_SESSION['CID'];
I'm not sure where the hold up is. The code you have will work:
$CID = wpCreateChimpCampaign(); // returns 'apple'
wpSendChimpTest($CID); // echos 'apple'
The code looks fine, but are you certain that all requirements are being met so both functions execute?
In other words are you supplying values for both $_REQUEST["subjectLine"] and $_REQUEST["testEmails"]?

A Sql function with 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.

where to put htmlspecialchars()

I am using the phpMyDataGird script to edit MySQL database tables through the web without using phpMyAdmin (I just use phpMyAdmin to manage the values but this script to manage the data)
The problem comes when I add HTML to a field. I want to be able to see them as code and not let them transform.
This is an example of how the script looks. If you click on a field you'll be able to edit it. In the first row, second column I wrote <i><b>someone</b></i> and as you can see it's not showing the code but is being bolded and italicized.
This is the main page of the script where I add my MySQL information and change settings, and this main page is connected to a page where all the script is written.
Can anyone take a look at these pages and tell me where to add the htmlspecialchars() call because I have been trying, but it's not working.
If You want to show the HTML special chars only in the grid (and they can stay as they are) try to edit the line 1612 in a 'page' script - that should be a mask function:
function mask($value,$mask,$datatype,$aselect,$row){
switch ($datatype){
...
default:
/*1612 line here --> */ return htmlspecialchars($value);
}
}
But I'm not sure if this is what You want to achieve...
EDIT: to also save the data in htmlspecialchar formatted value, try to change the line 927 from
$strUpdate = "UPDATE $this->tablename set $value=".magic_quote($nt)." $updWhere Limit 1";
to
$strUpdate = "UPDATE $this->tablename set $value=".htmlspecialchars(magic_quote($nt))." $updWhere Limit 1";
but again, I'm not sure... If this is OK, then You can remove the htmlspecialchars in previous example (line 1612).

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