mysql wrong column increment - php

what is wrong with this code?
$core->query("UPDATE games SET hits = hits + 1 WHERE id=".intval($id).";");
hits incerements by 2 and sometimes by 3! I mean for example hits = 3; when I call this function, hits will be 5 and sometimes 6! (add 2 and 3 instead 1).
mysql table type is MyISAM.
query function is:
function query($query) {
$this->error="";
$this->result=#$this->link->query($query);
if(!$this->result) {
$this->error=#$this->link->error;
return FALSE;
}
return $this->result;
}
link is:
$link = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

The SQL code looks correct, so it must be the context that is causing the problem.
It is possible that you put the code in an element that gets called two or three times per page? If not explicitly, through an include or subroutine structure?

It seems that your query is correct but may be this function call for multiple time for same $id value. Please check this..
thanks

It was from flash on that page.

Related

Prevent "Commands Out of Sync" error from MySQL stored procedure called via AJAX

I have a MySQL stored procedure that updates data across a set of tables (basically for one record in the principal table and related records in a set of child tables). It's called via AJAX through a PHP function. (That is, the AJAX call is to a PHP page, which ultimately calls this SP.) It was working fine, but now I'm trying to make it do one more thing and running into the "Commands out of sync; you can't run this command now" error.
The change is to store one more item in the principal table, but to do so may require adding an item to a child table (called ActionTopic). The page lets the user either choose from a dropdown or type in a new value. I've added two parameters to the SP: one is the PK chosen in the dropdown, the other is the new value typed in. In the SP, I've added the code below. It checks whether there was a new value typed in. If so, it calls another SP that checks whether the value typed in is already in the table and, if not, adds it. (I've tried with the code to check and add the record inline rather than in a separate SP and I have the same problem.)
if cNewTopic <> '' then
-- First, make sure the new topic isn't already there
call aoctest.AddActionTopic(cNewTopic);
-- SELECT #iTopicID := iID FROM ActionTopic WHERE UPPER(Description) = UPPER(cNewTopic);
SET #iTopicID = LAST_INSERT_ID();
else
SET #iTopicID = Topic;
end if;
The page works if the user makes a choice from the dropdown. The problem only occurs when the user types in a new value. Even when I get the error, everything else works as expected. The new value is added to the child table, and the parent table and other children are updated as expected.
Interestingly, if I call the SP in MySQL Workbench with the same parameters (after ensuring that the new value isn't in the new table), it runs without error. The only odd thing I've noticed is that I get two rows in the Output section of MySQL Workbench rather than one. Both show the call to the SP. The first shows "1 row(s) returned" and a period of time, while the second shows "0 row(s) returned" and "-/0.000 sec". A call to the SP in MySQL Workbench where the new value is already in the table also shows two rows in the Output section, but the second one shows "1 row(s) returned".
Not sure whether any of the other code is needed here. If you think I need to show more, please ask.
UPDATE: Based on the comment from Pete Dishman, I took a harder look at where the error is occurring. It's not the original SP call giving an error. It's the next call to MySQL, which is still inside the Ajax call.
The code processing the result already had this code:
//not sure why next line should be needed.
mysqli_next_result($conn);
I tried both simply doubling the call to mysqli_next_result (that is, two in a row) and putting it into a loop along the lines Pete suggested. With two calls, I still get the same error. With a loop, I wait 30 seconds and then get error 500: Internal server error.
UPDATE 2: I tried with a loop for mysqli_more_results() (similar to the one in Pete Dishman's reply) and echoing a counter inside the loop. The code brought my internet connection to a crawl and I finally had to break out of it, but there were dozens of iterations of the loop. Just tried the following:
mysqli_free_result($result);
$result = mysqli_store_result($conn);
mysqli_free_result($result);
if (mysqli_more_results($conn)) {
$result = mysqli_store_result($conn);
mysqli_free_result($result);
}
$allresult = getsubmissions($conn);
Found a noticeable delay before it failed.
Even if you can't tell me what's wrong, I'd appreciate ideas for how to debug this.
This may be because the stored procedure is returning multiple result sets (the two rows in workbench).
When querying from php you need to retrieve both result sets before you can send another query, otherwise you get the "commands out of sync" error.
The documentation seems to imply this is only the case when using mysqli_multi_query but we have it in our code when using mysqli_real_query.
Our query code is along the lines of:
mysqli_real_query($conn, $sql);
$resultSet = mysqli_store_result($conn);
while (!is_null($row = mysqli_fetch_array($resultSet, MYSQLI_BOTH)))
{
$results[] = $row;
}
mysqli_free_result($resultSet);
// Check for any more results
while (mysqli_more_results($conn))
{
if (mysqli_next_result($conn))
{
$result = mysqli_store_result($conn);
if ($result !== FALSE)
{
mysqli_free_result($result);
}
}
}
return $results;
The code would be different obviously if you're using PDO, but the same principle may apply (See http://php.net/manual/en/pdostatement.nextrowset.php)
I've solved my own problem by reworking the code that processes the result as follows:
if (mysqli_more_results($conn)) {
mysqli_free_result($result);
mysqli_next_result($conn);
$result = mysqli_store_result($conn);
mysqli_free_result($result);
if (mysqli_more_results($conn)) {
mysqli_next_result($conn);
$result = mysqli_store_result($conn);
if (!is_null($result) and gettype($result)!== 'boolean') {
mysqli_free_result($result);
}
}
}
$allresult = getsubmissions($conn);

How to count the colums in a certain database table + more and show it on website (with php)

I need my visitors on homepage to see how many active user we have. I need to include this with php. (need the code)
in mysql database user is marked with 0 (inactive) and 1 (active).
How can I count/read out the outcome, means all active users, of the database(database_name) - table(user_registration) - colums(each_one) - count(status)?
How to publish this on my website?
Would prefer to this in php cause i'm not so used to js and query.
A simple methode/explanation would be very nice.
Thank you.
(need the code) first this is not a script writing service. Come up with some try and we will try giving a solution.
Basic necessity for your required active user count is to have a status (or name it something) column in your user table.
Then, while a user logs in change the status from 0 to 1 while logs out change it from 1 to 0
by doing so you could easily query it to display the active user.
select column,column from table where status = 1
//(i.e)
select id,userName from users where status = 1
Try using ajax if you want to display it like on-line users displayed in fb
In our implementation, I created a separate DB table active_users, wrote a php function to write user_id and timestamp to this table. This function is called via ajax from your page, bind it to whatever user action you see fit (in our case it is a search).
Write another php function that queries the said tables and retrieves users with time difference between the timestamp and now less than specific value (in our case 5 min). call this function from your page via ajax either in specific time intervals (heartbeat) or user action again - mouse move etc. Display results of this call somewhere (in our case "Active Users" div)
this is what i have.
it works good, but it just shows the amount of lines within.
How can i count all numbers in 'status' within those lines?
<?php
$con = mysql_connect($dbHost, $dbUser, $dbPass );
mysql_select_db($dbName, $con);
$res = mysql_query('SELECT Count(*) FROM ' . 'user_registration', $con);
if ($row = mysql_fetch_array($res, MYSQL_NUM))
{
$users = trim($row[0]);
}
else
{
$users = 'Error';
}
?>
to Show result on website:
<?= $users ?>

PHP - Login script not working correctly

I have a question for you.
I am creating an administration panel, this is the first time for me, and I have some problems.
1. Problem
I am using mysqli_fetch_assoc() in this way:
$row_cnt = mysqli_fetch_assoc($result);
printf('Result set has %d rows.<br />', $row_cnt);
if ($row_cnt['COUNT(id)'] == 0) {
return false;
} else {
return true;
}
I use this to see if in the DB there are some entries, it returns 1 everytime, whatever thing I insert in the fields. I thought that it has to return 0 if there are no entry in the DB, am I wrong?
Please be patient, this is my first login page with admin panel.
Just from taking a quick peek -
mysql_real_escape_string requires a connection to be established via mysql_connect, you need to use the mysqli_real_escape... function - http://php.net/manual/en/mysqli.real-escape-string.php
You don't specify what SQL you are actually using, but assuming it is something similar to
Select Count(*) from mytable where myvalue= 'Something'
The RowCount will always be one 1 as The Count will always be returned.

Creating link to database

I am currently making a project on Universal Identification Number(not such a big one, but like that kind of....upto college level)..I want to create a page with tabs to the respective databases.... like If I press key 'A' for a tab then all the names starting with letter 'A' should appear...
Plz help me !!!!
Regards !!
Not entirely understanding your question, but if I was to create a tab for different names, and/or situations, I'd use a switch statement with cases that allows you to change the order_by in your sql query.
I think this is kinda what you want to display all names starting with an A passed on with a get request:
<?php
//connect to mysql database (if you don't know search google)
if(isset($_GET['namestartingwith'])){
$namebegin = $_GET['namestartingwith'];
$query = mysql_query("SELECT * FROM database WHERE name LIKE \"$namebegin%\"");
while(mysql_fetch_array($query) = $data){
echo $data['name'];//name being the name op your column with the name data
}
}
?>
This should do the trick for php+mysql
In Java+MySQL, after downloading and instating the requisite jars:
public static Connection dbConnect() throws SQLException, ClassNotFoundException {
String DB_URL;
Class.forName("com.mysql.jdbc.Driver");
DB_URL = "jdbc:mysql://your_db_url?autoReconnect=true";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
return conn;
}
In the calling program,
public static Object dbExecute() throws SQLException, ClassNotFoundException {
Statement stmt;
Connection conn = dbConnect();
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("your_sql_statement");
Object result = null;
while (rs.next()) {
result = rs.getObject("field_you_want_to_retrieve");
}
rs.close();
stmt.close();
conn.close();
return result;
}
I think you need to take this from the start. Are you using PHP or Java? Are you using MySQL or Oracle for your database? Maybe set yourself a simpler goal, build a PHP page (or Java servlet) that fetches data from your database and displays it in a table in the web browser. When you get this working, you can build on it.
When you get to a question that you can't answer, then submit that question to Stackoverflow. Explain what you have working, what you are trying to do and where the expected result deviates from the actual result.

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