how to get two rows from sql database - php

I have a table in sql database named releases this table has 2 rows with the same id like (260) now I would like to get this two rows into my php file I used this function (mysqli_fetch_assoc) but the output gives one single row only (in array) and didn't give me the other one. So how can I get the two rows with array and how to call specific record from this array ???
Here is my code:
$conn = mysqli_query($db,"SELECT * FROM ps4_media_releases_ref LEFT JOIN ps4_releases ON ps4_media_releases_ref.rid=ps4_releases.release_id
WHERE mid = {$media_id2}");
$result=mysqli_fetch_assoc($conn);
$result2=mysqli_num_rows($conn);

Possible solution is (irrespective of technology, modify according to technology)
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
example
SELECT *
FROM Persons
WHERE ROWNUM <=2;

I am sure there is nothing wrong with php code you have written.
The problem is with query.
Just run your query in my sql client and double confirm that it returns two rows.
Note:
In Doubt double check the count of the associative array returned
echo count($result)
-- Update
mysql_fetch_assoc
will return one row at a time till it returns all the row
so try below code snippet
while ($row = mysql_fetch_assoc($result)) {
echo $row["RecordName or ColumnName"];
///Get as many records as you want
}

Related

How can I count entries in mySQL database faster?

I am counting the entries in my SQL database:
$sql = "SELECT * FROM files WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute([$id]);
$rowCount =$q->rowCount();
The result of $rowCount is 500000.
But to output this single number takes 5 seconds! Is it possible to get this result faster?
Use the COUNT() function https://dev.mysql.com/doc/refman/8.0/en/counting-rows.html:
$sql = "SELECT COUNT(*) FROM files WHERE id = ?";
Also ensure that 'id' is an indexed column:
https://dev.mysql.com/doc/refman/8.0/en/mysql-indexes.html
Replace * with a field(use auto-increment id) - This will reduce the time a bit.
Index that field. - If you use indexed field the query performance will increase.
SELECT * ..., then counting in PHP, requires shoveling all columns of all rows back to PHP. That's a lot of effort for very little gain.
SELECT COUNT(col) ... does the counting in by MySQL, but it must check for whether col is NULL. And it needs to get at the value of col for every row.
SELECT COUNT(*) ... counts the rows by whatever way is most efficient. This involves looking for the 'smallest' index (or the whole table, if no secondary indexes), and counting through it.
You must learn about INDEXes to get anywhere in databases! This is only one minor use for them.

Get count from mysql_num_rows result

I have a form that collects RSVPs for a party. The person filling out the form (Name) has an option to bring a guest (Guest). In the notification email, I am trying to give an accurate count of RSVPs with total Name and Guest counts.
It is easy to do if I was just getting the Name count (for person filling out the form):
mysql_query($query);
$result = mysql_query("select * from tablename");
$rowCount = mysql_num_rows($result);
mysql_close($link);
and I would simply use $rowCount as the total number of RSVPs. But I also want to include Guests in the count. The Guest is entered as GuestFirstName and GuestLastName in the form and goes on the same record as the person filling out the form. So I tried this. It worked when I included a guest - it said total RSVPs were 2. But when I did not include a guest on the next test I did, it also counted it as 2. Here is the code I used for that:
mysql_query($query);
$result = mysql_query("select * from tablename");
$result_guest = mysql_query("select * from tablename WHERE
GuestFirstName IS NOT NULL);
$rowCount = mysql_num_rows($result) + mysql_num_rows($result_guest) ;
mysql_close($link);
Like I said, this code yields 2 RSVPs even when no guest is entered. Any help would be appreciated. Thanks.
cdr6800
and
You can achieve this in a single query like the following. Also try to use PDO or mysqli_* functions because you use mysql_* which are deprecated.
SELECT
COUNT(*) AS total_names,
COUNT(CASE WHEN GuestFirstName IS NOT NULL THEN 1 END) AS total_guests
FROM tablename;
So, if there are 10 invitation rows and only 4 of them have guests results will be:
total_names total_guests
10 4
That's an expensive way to get a count of rows: selecting all columns from all rows in the table, and fetching those from the database to the client, to get just a "count" of the number of rows.
SQL provides aggregate functions. For example COUNT() can be used to return a count of rows.
As far as why you are getting two rows returned...
WHERE GuestFirstName IS NOT NULL
The most likely explanation is that there are two rows in the table which have a non-NULL value assigned to the GuestFirstName column. It may be an empty (zero-length string), which isn't considered NULL. Consider
SELECT '' IS NULL -- 0 (false)
, '' IS NOT NULL -- 1 (true)
I think you probably also want to exclude from the count rows where the GuestFirstName is equal to the empty string.
The PHP mysql_ extension is deprecated, and will be removed in future release. Two suitable replacements are available: PDO and mysqli.
And use a query that returns a single row with a count of rows. That will be more efficient than returning the entire table, just to get a count.
And do it in one pass through the data. For a row that includes a Guest, increment the count by 2, otherwise increment the count by 1. Use a SUM() aggregate, with an expression that returns either 2 or 1.
For example:
SELECT SUM(IF(t.GuestFirstName<>'',2,1)) AS total_including_guests
, SUM(1) AS count_rsvp
FROM mytable t
Maybe Guest Name has an empty (but not null) value. Try:
$result_guest = mysql_query( select * from tablename
WHERE GuestFirstName IS NOT NULL
AND GuestFirstName != '');
You can actually do this with one query and no additional logic, using SUM()
SELECT SUM(IF(GuestFirstName IS NULL, 1, 2)) AS totalGuests FROM tablename;
This will iterate over all rows and and sum up 1 (if 1 guest in this row is coming) or 2 (if "main" guest + his invite are coming)

Addition from MySQL query

I am trying to add this:
if (question_counter==10){
$query3 = "SELECT answer_points WHERE participation_id=".$participation_id;
$dbc->query($query3)
}
This is supposed to get all the answer_points where the participation_id = "something". This happens when I receive in my PHP function that question_counter has reached 10
I now want to perform an addition between all the results I receive in my query above so that I can find out a total score and store it as a variable.
How would I go about doing this efficiently?
I thought about writing queries for each answer where I get the participation_id and the question_counter to write the query, store each row result in a separate variable and add all those together. I think this is an overkill and dumb since I will have to write 10 queries to get each row's result.
Anyway this is my Table
You can use MySQL's SUM function.
SELECT SUM(columnName) AS totalScore FROM tableName WHERE id = 34;
Your query is not correct.
$query3 = "SELECT answer_points FROM table_name WHERE participation_id=".$participation_id;
^^^^^^^^^^^^^^^
from and table name
You have forgot from and table name in the query.
To get the sum of the column you need to use the SUM function of mysql.
Here is tutorial of SUM function in mysql.
You have to write query using SUM function
$query3 = "SELECT SUM(answer_points) AS answer_points
FROM TABLE_NAME
WHERE participation_id=".$participation_id;

Select on empty table but still get column names

I want to do a SELECT on an empty table, but i still want to get a single record back with all the column names. I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query.
I know this one works when i run it directly in MySQL:
SELECT * FROM cf_pagetree_elements WHERE 1=0;
But i'm using PHP + PDO (FETCH_CLASS). This just gives me an empty object back instead of an row with all the column names (with empty values). So for some reason that query doesn't work with PDO FETCH_CLASS.
$stmt = $this->db->prepare ( $sql );
$stmt->execute ( $bindings );
$result = $stmt->fetchAll ( \PDO::FETCH_CLASS, $class );
print_r($result); // Empty object... I need an object with column names
Anyone any idea if there's another method that i can try?
Adding on to what w00 answered, there's a solution that doesn't even need a dummy table
SELECT tbl.*
FROM (SELECT 1) AS ignore_me
LEFT JOIN your_table AS tbl
ON 1 = 1
LIMIT 1
In MySQL you can change WHERE 1 = 1 to just WHERE 1
To the other answers who posted about SHOW COLUMNS and the information scheme.
The OP clearly said: "I know there are other ways to get the column names from a table, but i want to know if it's possible with some sort of SELECT query."
Learn to read.
Anyway, to answer your question; No you can't. You cannot select a row from an empty table. Not even a row with empty values, from an empty table.
There is however a trick you can apply to do this.
Create an additional table called 'dummy' with just one column and one row in it:
Table: dummy
dummy_id: 1
That's all. Now you can do a select statement like this:
SELECT * FROM dummy LEFT OUTER JOIN your_table ON 1=1
This will always return one row. It does however contain the 'dummy_id' column too. You can however just ignore that ofcourse and do with the (empty) data what ever you like.
So again, this is just a trick to do it with a SELECT statement. There's no default way to get this done.
SHOW COLUMNS FROM cf_pagetree_elements;
This will give a result set explaining the table structure. You can quite easily parse the result with PHP.
Another method is to query the infomrmation schema table:
SELECT column_name FROM information_schema.columns WHERE table_name='cf_pagetree_elements';
Not really recommended though!
You could try:
SELECT * FROM information_schema.columns
WHERE table_name = "cf_pagetree_elements"
Not sure about your specific PHP+PDO approach (there may be complications), but that's the standard way to fetch column headings (field names).
this will list the columns of ANY query for PDO drivers that support getColumMeta. I am using this with SQL server and works fine even on very complex queries with aliased tables, sub-queries and unions. Gives me columns even when results are zero
<?php
// just an example of an empty query.
$query =$PDOdb->query("SELECT * from something where 1=0; ");
for ($i=0; $i<$query->columnCount(); $i++) {
echo $query->getColumnMeta($i)['name']."<br />";
}
?>
Even without PDO in the way, the database won't return the structure without at least one row. You could do this and ignore the data row:
SELECT * FROM cf_pagetree_elements LIMIT 1;
Or you could simply
DESC cf_pagetree_elements;
and deal with one row per field.
WHERE 1=0 does not work for me. It always returns empty set.
The latest PDO for SQLSVR definitely works with get column meta.
Simply set up your statement and use this to get an array of useful information:
$stmt->execute();
$meta= array();
foreach(range(0, $stmt->columnCount() - 1) as $column_index)
{
array_push($meta,$stmt->getColumnMeta($column_index));
}
Complete solution for Oracle or MySQL
for any or some columns (my goal is to get arbitrary columns exactly as they are in DB regardless of case)
for any table (w or w/o rows)
$qr = <<<SQL
SELECT $cols
FROM (SELECT NULL FROM DUAL)
LEFT JOIN $able t ON 1 = 0
SQL;
$columns = array_keys($con->query($qr)->fetchAll(PDO::FETCH_ASSOC)[0]);
if($cols === "*") {
array_shift($columns);
}
YOu could use MetaData with;
$cols = mysql_query("SHOW COLUMNS FROM $tableName", $conn);

Check already made query for distinct field values but without making other query

I am trying to make menu with multiple submenus.I need to make query that takes the result of preceding query and leaves only distinct results of some field.If i make new query each time the server bugs because the query searches through veri big database.
So in short something like that :select distinct(field) form(already made query)
Is there any way in mysql or php tthat this can be done?
Can you not just use a subquery? SELECT DISTINCT field FROM (SELECT * FROM menus WHERE ...)
More information on subqueries in MySQL. A subquery will let you do the outer select, against the results of the inner select.
in php you can loop on the first query result an build an array containing distinct fields:
$result = mysql_query($sql);// result of 1st query
$arr = array();//an array that will contain distinct field values
while ($row = mysql_fetch_assoc($result)) {// for each row
if (!in_array($row["field"], $arr)) // check if it's not in the array
$arr[] = $row["field"] // add it
}

Categories