I want to perform join on two table in codeigniter
Table 1: (registered_cname)
roll_no(int),name(varchar);
Table 2: (student_registered)
roll_no(int),status(varchar),company_name(varchar)
Query Code:
$this->db->select($table.'.roll_no,student_placement.stud_name,student_placement.status,student_placement.company_name');
$this->db->from($table);
$this->db->join('student_placement', $table.'.roll_no = student_placement.roll_no');
$this->db->where_in('student_placement.status',$dept);
$this->db->get();
To debug this you need to examine and test the generated SQL.
You can do so by adding the following to the end of your SQL...
echo $this->db->last_query(); // DEBUG
And you might need to add in an exit() to trap it depending upon your code.
echo $this->db->last_query(); // DEBUG
exit();
And look at the SQL and even copy and paste it into your SQL Tool like phpmyadmin and see what happens.
That will give you an indication of what isn't correct.
So you don't have DEBUG code appearing and cant remember where it is, you can modify the exit to be ( and this is only a suggestion) ...
echo $this->db->last_query(); // DEBUG
exit(__FILE__ .' '.__LINE__);
There are also __METHOD__ and __CLASS__ magic constants you can use as well, if you feel so inclined.
Related
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!
i have a kind of problems here and i don't know how to solve it... google said nothing and the search function here didn't shown me anything...
i use this code
$GAME_DB = new mysqli($__CONFIG['MySQL']['HOST'], $__CONFIG['MySQL']['USER'], $__CONFIG['MySQL']['PASS'], $__CONFIG['MySQL']['DB']['GAME']);
if($GAME_DB->connect_errno) { echo $GAME_DB->connect_error; exit; }
$VILLAGE_DATA['villageID'] = $mysqli->real_escape_string($VILLAGE_DATA['villageID']);
$query = "SELECT name, level, time FROM actions WHERE type='build' AND villageID='".$VILLAGE_DATA['villageID']."'";
if($result = $GAME_DB->query($query))
{
// table header
while($row = $result->fetch_row())
{
// some rows in here
}
// table footer
}
there aren't any syntax errors in that query and the results are there!
sometimes the query is successful and i see my table but sometimes (for example: when i reload) i receive the error message Commands out of sync; you can't run this command now
how can this just work "sometimes"? where is my problem?
http://dev.mysql.com/doc/refman/5.6/en/commands-out-of-sync.html
If you get Commands out of sync; you can't run this command now in
your client code, you are calling client functions in the wrong order.
This can happen, for example, if you are using mysql_use_result() and
try to execute a new query before you have called mysql_free_result().
It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
But from the code you've posted I don't see how this could happen. Either there's more code than what you've posted and something there is happening out of order, or your MySQL connections are being improperly established/pooled/persisted somewhere outside of PHP.
I know it is a frequently asked question, but let me explain a bit why I need to ask that again.
Most answers out there suggests using
$this->db->affected_rows()
This is not working in my situation as I may have situation that the update data is the same as the data in the database, so it will return 0 even if the update is success.
I know I can write another query to check if it is because the data are the same, but this sounds stupid to me.
Another way is to use the Active Record Class in code igniter, so the line will be something like:
$error_num = $this->db->update("users", array('firstName' => $newFirstName));
return $error_num;
which is a better solution (at least it works even if there is no update due to repeated data). However, I would like to use the database class, i.e. something like:
$this->db->query('update table set field = somedata where id=1');
It increases the readability of my code to coder who knows php + SQL but are not familiar with code igniter, but then this is why I am asking if anybody knows how do I get the error number if I query in this way?
i.e. Something like mysql_errno() when using mysql_query($query) in PHP.
Both will work like same only difference
if you using active record class all the input variables are escaped automatically
If you want security you better to go with active record class
If you use normal query execution you have to escape the input parameters manually using $this->db->escape_str()
$id = $this->db->escape_str($id)
You can check the query execution status.
$status = $this->db->update("users", array('firstName' => $newFirstName));
if($status)
{
//here you can check the number of affected rows if required
echo $this->db->affected_rows();
}else{
//here you can prcess for failure case
log_message('Error', $this->db->_error_message());
}
//return the status to required place
return $status
I have use this code for checking.
$status = $this->db->query('update table set field = somedata where id=1');
if($status)
return true;
else
return false;
I have a very simple INSERT statement being executed from a PHP script running on a Linux Apache web server. I can run the query fine from within SQL Management Studio and it normally runs fine from PHP as well. However, every once in awhile I get an error message from my PHP script that the query failed and the mssql_get_last_message() function returns 'The statement has been terminated'.
What sources can cause this message to be returned from SQL Server?
You have found one of the most annoying parts of SQL Server. There are situations where an error can be raised, and SQL will generated two error messages: the first to explain what the error was, and the second to say something useful like "The statement has been terminated" (which, technically, is error number 3621). The thing is that SQL, and most everything else that touches it--such as PHP--can only see/pick up/process/or otherwise utilize that last unlcear error message. The one that's actually useful gets lost.
The quick way to figure out what's going on is to run the sequence of commands leading up to the error from SSMS. This, apparently, will not work for you.
A fussier way to figure it out is to fire up SQL Profiler to track the Exception event, and then run your process. This should show all errors that occured. Tossing in relevant other events (SP:Starting, SP:StmtStarting, SQL:BatchStarting, whatever is applicable to the code your submitting to the database) will show which command is raising the error.
To get a numeric error code from mssql you can do a select that looks something like
SELECT ##ERROR AS ErrorCode
Which SHOULD return the correct error code.
You can also try this code which is posted on PHP.NET.
function query($sQuery, $hDb_conn, $sError, $bDebug)
{
if(!$rQuery = #mssql_query($sQuery, $hDb_conn))
{
$sMssql_get_last_message = mssql_get_last_message();
$sQuery_added = "BEGIN TRY\n";
$sQuery_added .= "\t".$sQuery."\n";
$sQuery_added .= "END TRY\n";
$sQuery_added .= "BEGIN CATCH\n";
$sQuery_added .= "\tSELECT 'Error: ' + ERROR_MESSAGE()\n";
$sQuery_added .= "END CATCH";
$rRun2= #mssql_query($sQuery_added, $hDb_conn);
$aReturn = #mssql_fetch_assoc($rRun2);
if(empty($aReturn))
{
echo $sError.'. MSSQL returned: '.$sMssql_get_last_message.'.<br>Executed query: '.nl2br($sQuery);
}
elseif(isset($aReturn['computed']))
{
echo $sError.'. MSSQL returned: '.$aReturn['computed'].'.<br>Executed query: '.nl2br($sQuery);
}
return FALSE;
}
else
{
return $rQuery;
}
}
You can use the code in the message to know which is the error. For example:
[2627: The statement has been terminated.]
In this case, the error code is 2627, so if you execute the sql below you'll know the message
SELECT msg.text
FROM sys.messages msg
INNER JOIN sys.syslanguages lng ON lng.msglangid = msg.language_id
WHERE msg.message_id = 2627
AND lng.alias = 'English'
Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in
object '%.*ls'. The duplicate key value is %ls.
This is a way to know the right message error. In my example the error is violation of primary key
I'm probably going to make myself look like a fool with my horrible scripting but here we go.
I have a form that I am collecting a bunch of checkbox info from using a binary method. ON/SET=1 !ISSET=0
Anyway, all seems to be going as planned except for the query bit. When I run the script, it runs through and throws no errors, but it's not doing what I think I am telling it tom which is updating the specified fields within the DB.
I've hard coded the desired values into the query and it DOES update the DB. Relying on the variables I believe I've established and am then calling upon in the query does NOT update the DB.
I've also tried echoing all the needed variables after the script runs and exiting right after so I can audit them... and they're all there. Here's an example.
####FEATURES RECORD UPDATE
### HERE I DECIDE TO RUN THE SCRIPT BASED ON WHETHER AN IMAGE BUTTON WAS USED
if (isset($_POST["button_x"])) {
### HERE I AM ASSIGNING 1 OR 0 TO A VAR BASED ON WHTER THE CHECKBOX WAS SET
if (isset($_POST["pool"])) $pool=1;
if (!isset($_POST["pool"])) $pool=0;
if (isset($_POST["darts"])) $darts=1;
if (!isset($_POST["darts"])) $darts=0;
if (isset($_POST["karaoke"])) $karaoke=1;
if (!isset($_POST["karaoke"])) $karaoke=0;
if (isset($_POST["trivia"])) $trivia=1;
if (!isset($_POST["trivia"])) $trivia=0;
if (isset($_POST["wii"])) $wii=1;
if (!isset($_POST["wii"])) $wii=0;
if (isset($_POST["guitarhero"])) $guitarhero=1;
if (!isset($_POST["guitarhero"])) $guitarhero=0;
if (isset($_POST["megatouch"])) $megatouch=1;
if (!isset($_POST["megatouch"])) $megatouch=0;
if (isset($_POST["arcade"])) $arcade=1;
if (!isset($_POST["arcade"])) $arcade=0;
if (isset($_POST["jukebox"])) $jukebox=1;
if (!isset($_POST["jukebox"])) $jukebox=0;
if (isset($_POST["dancefloor"])) $dancefloor=1;
if (!isset($_POST["dancefloor"])) $dancefloor=0;
### I'VE DONE LOADS OF PERMUTATIONS HERE... HARD SET THE 1/0 VARS AND LEFT THE $estab_id TO BE PICKED UP. SET THE $estab_id AND LEFT THE COLUMN DATA TO BE PICKED UP. ALL NO GOOD. IT _DOES_ WORK IF I HARD SET ALL VARS THOUGH
mysql_query("UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'");
###WEIRD THING HERE IS IF I ECHO THE VARS AT THIS POINT AND THEN EXIT(); they all show up as intended.
header("location:theadminfilething.php");
exit();
THANKS ALL!!!
I recommend you to use something like:
$fields = array('pool', 'darts', 'karaoke', 'trivia', ...);
foreach ( $fields as $field ) {
$$field = isset($_POST[$field]) ? 1 : 0;
}
instead of 20 lines of ifs.
Your columns are ENUM or int type ? If int - drop apostrophes.
Your code could really use some error checking. Make sure you have activated the displaying of errors in your script.
In your testing environment add this at the top of your main script for instance (if you haven't done something equivalent already):
error_reporting( E_ALL | E_STRICT );
ini_set( 'display_errors', 1 );
Then (although not dependant on the above) make sure you probe the result of the query with something like:
if( false === mysql_query( 'UPDATE ...etc' ) )
{
echo 'query failed with error:' . mysql_error();
}
My guess is it will fail with the error that your column name karaoke is mispelled. But there may be more errors.
Also, hsz' suggestions are spot on (though probably not the root of your problem). Makes for easier to maintain code, and significantly reduces code.
Firstly, construct the sql query string in a variable and then pass it to mysql_query(), comment out the header() line and print out the query for debugging. For example:
...
$sql="UPDATE thedatabase SET pool_table='$pool', darts='$darts', karoke='$karaoke', trivia='$trivia', wii='$wii', megatouch='$megatouch', guitar_hero='$guitarhero', arcade_games='$arcade', dancefloor='$dancefloor' WHERE establishment_id='22'";
print("$sql");
mysql_query($sql);
//header("location:theadminfilething.php");
exit();
...
Secondly, even tho you are exiting the script, its good practice to always match your braces. You are missing the end brace for the if statement at the end of your code.
The value of the $sql variable output you can see if it works by executing it 'manually' thru phpmyadmin or the command line. What happens?