This is gonna be a dumb question, but I've been working with this code for years and never stopped to understand the what and why....
This is a very typical query I would copy and edit:
mysql_select_db($database_db, $db);
$query_qry_details = sprintf("Select * from table where id = %s", $KTColParam1_qry_details);
$qry_details = mysql_query($query_qry_details, $db) or die(mysql_error());
$row_qry_details = mysql_fetch_assoc($qry_details);
$totalRows_qry_details = mysql_num_rows($qry_details);
What do all these rows mean?
The first I know looks up the correct database. I have this line before each query on the page....do I need this?
The second row ($query_qry_details) is the query itself. I see that.
Rows 3 and 4 - no clue...
Row 5 is obviously a count of the number rows the query returns.
Thanks in advance as always.
EDITED
Shortly:
mysql_select_db(database_name, link_identifier) - Sets the cuurent active database on server that is associated with the specified link identifier.
sprintf - Return formatted string which acts as a query.
mysql_query or die - Sends a unique query to the database previously specified or exit from query.
mysql_fetch_assoc - Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead.
mysql_num_rows - Retrieves the number of rows from a result set.
Related
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 2 years ago.
I hope you all have a good day.
Actually I'm deploying a query to get a complete array of data. But the fact is that I need an Id, first of all, I guess, I must get the last Id first, then I can apply a mathematic operation to get its value + 1. The fact is that I've been trying different sentences and queries with no result.
This is my code:
function obtener_Id(){
global $mysqli;
$resultado_oId = $mysqli ->query("SELECT TOP 1 'id' FROM 'pacient' ORDER BY RowID DESC ")
$id_sacada = mysqli_fetch_assoc($resultado_oId);
$id_enLaMano = $id_sacada['id'];
return $id_enLaMano;
//$id_dinamica = $id_enLaMano + 1;
//return $id_dinamica;
}
As you can see guys, I've commented on the last two lines, cause I´m looking to get at least a value (The result from a query) But Idk if that is correct. Looking on the Internet I've seen relative posts which are solved just to apply the query that we can view under global declarations...
I've tried that on phpMyAdmin with no results and a bunch of errors...
You guys know the correct way to get the max value in the Id column? Or even if I'm doing badly correct me.
A lot of hugs and Luck!
Mizar ^^
I would suggest putting the serial number in a table. Read the serial no before insert, (lock the table, if required) insert the data, then increase the serial no by 1 and update the serial no table with increased value.
I want to print the number of rows retrieved from an updateQuery() statement in JDBC (mysql database). The code I have till now is this:
int rows=0;
//constructor sets this up like opening connection, etc...
String buildSelectQuery = buildSelectQueryForCode();
stmt = connection.createStatement();
rows= stmt.executeUpdate(buildSelectQuery); <---- mismatch
System.out.println(rows);
Where buildSelectQuery is CREATE VIEW viewName AS (SELECT * FROM tableName WHERE gen-congruence>1). There is a getRows method as well in the class:
public String getRows(){
return Integer.toString(rows);
}
Now, this query should ideally pull out over 2000 records and this is done in the view as well (in the database actually) but the getRows (which is being called in the GUI) prints out incorrect number of rows in the view (0) and I have no idea why. Is there another method to setup the result set? Am I doing something wrong? Please help me.
Your query is creating a view, not selecting from the view, so no rows are returned. You need to update rows when some rows are read.
I have the following codes..
echo "<form><center><input type=submit name=subs value='Submit'></center></form>";
$val=$_POST['resulta']; //this is from a textarea name='resulta'
if (isset($_POST['subs'])) //from submit name='subs'
{
$aa=mysql_query("select max(reservno) as 'maxr' from reservation") or die(mysql_error()); //select maximum reservno
$bb=mysql_fetch_array($aa);
$cc=$bb['maxr'];
$lines = explode("\n", $val);
foreach ($lines as $line) {
mysql_query("insert into location_list (reservno, location) values ('$cc', '$line')")
or die(mysql_error()); //insert value of textarea then save it separately in location_list if \n is found
}
If I input the following data on the textarea (assume that I have maximum reservno '00014' from reservation table),
Davao - Cebu
Cebu - Davao
then submit it, I'll have these data in my location_list table:
loc_id || reservno || location
00001 || 00014 || Davao - Cebu
00002 || 00014 || Cebu - Davao
Then this code:
$gg=mysql_query("SELECT GROUP_CONCAT(IF((#var_ctr := #var_ctr + 1) = #cnt,
location,
SUBSTRING_INDEX(location,' - ', 1)
)
ORDER BY loc_id ASC
SEPARATOR ' - ') AS locations
FROM location_list,
(SELECT #cnt := COUNT(1), #var_ctr := 0
FROM location_list
WHERE reservno='$cc'
) dummy
WHERE reservno='$cc'") or die(mysql_error()); //QUERY IN QUESTION
$hh=mysql_fetch_array($gg);
$ii=$hh['locations'];
mysql_query("update reservation set itinerary = '$ii' where reservno = '$cc'")
or die(mysql_error());
is supposed to update reservation table with 'Davao - Cebu - Davao' but it's returning this instead, 'Davao - Cebu - Cebu'. I was previously helped by this forum to have this code working but now I'm facing another difficulty. Just can't get it to work. Please help me. Thanks in advance!
I got it working (without ORDER BY loc_id ASC) as long as I set phpMyAdmin operations loc_id ascending. But whenever I delete all data, it goes back as loc_id descending so I have to reset it. It doesn't entirely solve the problem but I guess this is as far as I can go. :)) I just have to make sure that the table column loc_id is always in ascending order. Thank you everyone for your help! I really appreciate it! But if you have any better answer, like how to set the table column always in ascending order or better query, etc, feel free to post it here. May God bless you all!
The database server is allowed to rewrite your query to optimize its execution. This might affect the order of the individual parts, in particular the order in which the various assignments are executed. I assume that some such reodering causes the result of the query to become undefined, in such a way that it works on sqlfiddle but not on your actual production system.
I can't put my finger on the exact location where things go wrong, but I believe that the core of the problem is the fact that SQL is intended to work on relations, but you try to abuse it for sequential programming. I suggest you retrieve the data from the database using portable SQL without any variable hackery, and then use PHP to perform any post-processing you might need. PHP is much better suited to express the ideas you're formulating, and no optimization or reordering of statements will get in your way there. And as your query currently only results in a single value, fetching multiple rows and combining them into a single value in the PHP code shouldn't increase complexety too much.
Edit:
While discussing another answer using a similar technique (by Omesh as well, just as the answer your code is based upon), I found this in the MySQL manual:
As a general rule, you should never assign a value to a user variable
and read the value within the same statement. You might get the
results you expect, but this is not guaranteed. The order of
evaluation for expressions involving user variables is undefined and
may change based on the elements contained within a given statement;
in addition, this order is not guaranteed to be the same between
releases of the MySQL Server.
So there are no guarantees about the order these variable assignments are evaluated, therefore no guarantees that the query does what you expect. It might work, but it might fail suddenly and unexpectedly. Therefore I strongly suggest you avoid this approach unless you have some relaibale mechanism to check the validity of the results, or really don't care about whether they are valid.
Hi I have this Query and I'm getting an empty result, Anyone see anything obviously wrong with this?
SET SQL_BIG_SELECTS=1;
SELECT sector, SUM((fleetnow)+(fleetsoon)) AS Count
FROM AEDatabase
INNER JOIN AEPlayer AS Own ON AEDatabase.owner = Own.id
INNER JOIN AEPlayer AS Occ ON AEDatabase.occer = Occ.id
WHERE Galaxy='L49' AND (Own.guild='1085' OR Occ.guild='1085')
GROUP BY sector
Specific message from MySQL is:
"MySQL returned an empty result set (i.e. zero rows). ( Query took 0.4441 sec )"
Thanks for any help anyone can give.
If SQL request is composed correctly according to your business logic, and it returns no data it means, that either AEPlayer doesn't contain related data or AEDatabase doesn't contain any data related to Galaxy='L49'
You should separate all components of your request to determine what exactly collapses the result set.
I am trying to count the number of dates that occur for a specific mem_id, however, my count output is always "0"... heres my code:
$datechecker = $postdate;
//$postdate is a date variable that is posted via a form into mysql, stored as a DATE
$sql = mysql_query("SELECT * FROM members WHERE mem_id='$id' AND postdate='$datechecker'");
$Counter = mysql_num_rows($sql);
if($Counter >= 0) {
echo "$datechecker $Counter";
exit();
}
This is the output I get: 2011-01-01 0
Even though I have about 10 occurrences of 2011-01-01, so why does my count say "0"? Can anyone help me solve this, or provide an alternate?
echo the string before you mysql_query it, this will validate if the query is what you expect it to be. You can also use count(*) within the query, instead of using php's mysql_num_rows()
I also hope that you're sanitising your input before you're querying that!
1) You didn't clean $postdate, who knows if it conforms to MySQL's definition of DATE?
2) You didn't show us how your members table looks like. Is mem_id primary key? If it is, then of course you're going to get 1 row out of it.
3) You aren't checking whether your query succeeds or not, you immediately pass the resource_id to the mysql_num_rows table - which is a wrong way to perform counting anyway because MySQL (like any other relational database) has inbuilt mechanisms of counting rows based on criteria.
My guess is that your query is failing, seeing there's not $id specified.