mysql data being inserted twice via php - 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.

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!

Passing function result into sqli

I'm new to this and I know I'm probably doing this entire thing the wrong way, but I've been at it all day trying to figure it out. I'm realizing there's a big difference between programming a real project of my own rather than just practicing small syntax-code online. So, I lack the experience on how to merge/pass different variables/scopes together. Understanding how to fit everything within the bigger picture is a completely different story for me. Thanks in advance.
What I'm trying to do, is to make the function "selectyacht" output data in a different location from where it's being called (in viewship.php). The output data (in viewship.php) needs to be only certain fields (not everything) returned and those results will be scattered all over the html page (not in a table). In addition to that, I have this variable: "$sqlstatement" (in sqlconn.php) that I'm trying to bring outside the function because I don't want to repeat the connection function every time. I tried a global variable, as much as I shouldn't, and it thankfully it gave me an error, which means I have to find a better way.
Basically my struggle is in understanding how I should structure this entire thing based on two factors:
To allow the second conditional statement in sqlconn.php to be typed
as least often as possible for different "selectyacht" functions
that will come in the future.
To allow the connection instance in sqlconn.php to reside outside the function since it will be used many times for different functions.
Returning data in a different place from where it's being called in viewship.php because the call will be a button press, not the results to be shown.
This is probably very simple, but yet it eludes me.
P.S. Some of this code is a copy/paste from other resources on the internet that I'm trying to merge with my own needs.
sqlconn.php
<?php
$servername = "XXXXXXXX";
$username = "XXXXXXXX";
$password = "XXXXXXXX";
$dbname = "XXXXXXXX";
// Instantiate the connection object
$dbconn = new mysqli($servername, $username, $password, $dbname);
// Check if the connection works or show an error
if ($dbconn->connect_error) {
die("Connection failed: " . $dbconn->connect_error);
}
// Create a query based on the ship's name
function selectyacht($shipname) {
global $sqlstatement;
$sqlstatement = "SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
}
// Put the sql statement inside the connection.
// Additional sql statements will be added in the future somehow from other functions
$query = $dbconn->query($sqlstatement);
// Return the data from the ship to be repeated as less as possible for each future function
if ($query->field_count > 0) {
while($data = $query->fetch_assoc()) {
return $data;
}
}
else {
echo "No data found";
}
// Close the connection
$dbconn->close();
?>
viewship.php
<html>
<body>
<?php include 'sqlconn.php';?>
<!-- ship being selected from different buttons -->
<?php selectyacht("Pelorus");?>
<br>
<!-- This is the output result -->
<?php echo $data["Designer"];?>
<?php echo $data["Length"];?>
<?php echo $data["Beam"];?>
<?php echo $data["Height"];?>
</body>
</html>
Mate, I am not sure if I can cover whole PHP coding standards in one answer but I will try to at least direct you.
First of all you need to learn about classes and object oriented programming. The subject itself could be a book but what you should research is autoloading which basically allows you to put your functions code in different files and let server to include these files when you call function used in one of these files. This way you will be able to split code responsible for database connection and for performing data operations (fetching/updating/deleting).
Second, drop mysqli and move to PDO (or even better to DBAL when you discover what Composer is). I know that Internet is full of examples based on mysqli but this method is just on it's way out and it is not coming back.
Next, use prepared statements - it's a security thing (read about SQL injection). Never, ever put external variables into query like this:
"SELECT * FROM ships WHERE Name=" . "'" . $shipname . "'";
Anyone with mean intentions is able to put there string which will modify your query to do whatever he wants eg. erase your database completely. Using prepared statements in PDO your query would look like this:
$stmt = $this->pdo->prepare("SELECT * FROM ships WHERE Name = :ship_name");
$stmt->bindValue(':ship_name', $shipname);
Now to your structure - you should have DB class responsible only for database connection and Ships class where you would have your functions responsible eg. for fetching data. Than you would pass (inject) database connection as an argument to class containing you selectYacht function.
Look here for details how implementation looks like: Singleton alternative for PHP PDO
For
'Returning data in a different place from where it's being called'
If I understand you correctly you would like to have some field to input ship name and button to show its details after clicking into it. You have 2 options here:
standard form - you just create standard html form and submit it with button click redirecting it to itself (or other page). In file where you would like to show results you just use function selectYacht getting ship name from POST and passing it to function selectYacht and then just printing it's results (field by field in places you need them)
AJAX form - if you prefer doing it without reloading original page - sending field value representing ship name via AJAX to other page where you use selectYacht function and update page with Java Script

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.

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.

How to periodically push data to the user interface in php

i need to implement a simple project using PHP and MySql in which i need to push data to the user's UI when some one else is updating the database, and i need to periodically do this too, so when some one else accessing the same table and modify it, another person who uses the UI can see the updates, sorry if i'm being silly but up to now i'm only aware of saving data to a database and retrieving and showing it to the user(simplest form of data base connection). how can i achieve this in php, please some one help me on this matter, if the answer explains the things in detail it is good, because i'm very novice to this.thanks in advance.
rangana.
If the web page has no data to return, then get the page to wait for a period while polling the database. You must use the sleep statement to avoid maxing out your server.
Warning: Some servers wont let the user open another page while one is in progress, which may cause you problems in some situations. So either dont hold the page open for too long, or maybe try to get the ajax page to use a different session.
// do this when you have put new data in to database
setappdata("lastupdate",microtime(true));
// use this loop to poll for new data
$loop = 0;
$lastupdate=$_SESSION["lastupdate"];
while ($lastupdate==$last=getappdata("lastupdate") and $loop<10) {
$loop++;
usleep(500000); //0.5sec
}
// use a table called appdata to store application data
function getappdata($var) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)<1) return false;
return mysql_result($res1,0,"data");
}
function setappdata($var,$data) {
$query = "SELECT data FROM appdata WHERE var='$var'";
$res1=mysql_query($query);
if (mysql_numrows($res1)>0) $query = "UPDATE appdata SET data='$data' WHERE var='$var'";
else $query = "INSERT INTO appdata SET var='$var',data='$data'";
return mysql_query($query);
}
These topics may get you started:
http://en.wikipedia.org/wiki/Push_technology
http://en.wikipedia.org/wiki/Reverse_Ajax

Categories