i have a total of 6 different tables that i select from then insert to a table before i do another select i was wondering if there was a way to skip the insert part and just do a select and combine all table data. the problem with the select and insert then select aproach is it gets really slow when there are about 1k+ records inserted. it takes about 30sec to 1min or more
im trying something like this
$sql = "select 1";
$statement = $conn->query($sql);
$rowset = $statement->fetchAll();
$sql1 = "select 2";
$statement1 = $conn->query($sql1);
$rowset1 = $statement1->fetchAll();
$combine = array_merge($rowset,$rowset1);
foreach ($combine as $key => $part) {
$sort[$key] = strtotime($part['date']);
}
array_multisort($sort, SORT_DESC, $combine);
To me it seems that you are replicating in php what you could do in sql. The above code in sql looks sg like this:
(select 1)
union all
(select 2)
order by date desc
You may have to tweak the order by clause depending on what data you exactly have in the date field. Otherwise, the above sql code should produce the exactly same results as your php code.
Related
i have a small problem. I use two mysql queries for getting data.
First i want to get IDs from groups
$sqlGoups = "SELECT * from `groups` WHERE `Date`='$TodayDate' ";
$result = $conn->query($sqlGoups);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$IDgroups = $row["ID"];
With that, I'll get those IDs, for example 5, 7, 12, 15, 22
I want to put them all in the next mysql query:
$sqlNext = "SELECT * FROM `orders` WHERE ID = '$IDgroups' ORDER BY `ID` ASC ";
$result = $conn->query($sqlNext);
When I do this, I get the result only for the first ID (5). And I want for each
I can not INNER JOIN tables because I use this in next query.
I tried with foreach loop, but no effect.
Try this code
SELECT * FROM `orders`
WHERE ID REGEXP CONCAT('(^|,)(', REPLACE('$IDgroups', ',', '|'), ')(,|$)')
ORDER BY `ID` ASC
Just like #Elanochecer commented the best bet should be a JOIN statement, but if you wish to go through your route, you could use the IN and provide the IDs as comma separated string, your query should look similar to the one below:
...
$sqlNext = "SELECT * FROM orders WHERE ID IN ('$IDgroups') ORDER BY ID ASC ";
...
Also, confirm if $IDgroups is in the format 1,2,3,4
If you provide the schema I could come up with a workable JOIN statement for you, preferably you can create a repo with the schema
I'm using PostgreSQL to get data and i want to insert it into MySQL. I have a php script which allows me to get the data, check for repeated and then insert it into MySQL DB. Problem is that instead of inserting only the non existing data it inserts one random row and doesn't insert nothing else.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
the variables $episode_col and $episode_values get data from an array called $episode through implode:
$episode_col = implode(", ", array_keys($episode));
$episode_values = implode("', '", array_values($episode));
This is you code.
IF statements are used for comparisons, yours is just fetching the array and there's no condition inside your IF statement. You need to fix the statements to get the columns and their respective values.
$check_for_episode = mysqli_query($conn, "SELECT DISTINCT house_number,number FROM episode WHERE house_number LIKE '".$house_number."' AND number = ".$episode_id_pg." LIMIT 1");
if (mysqli_fetch_array($check_for_episode)){
}else{
$insert_episode = mysqli_query($conn, "INSERT INTO episode(".$episode_col.")VALUES('".$episode_values."')");
}
You can try to use WHERE EXISTS or WHERE NOT EXISTS too.
SELECT DISTINCT column1 FROM table1
WHERE EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
SELECT DISTINCT column1 FROM table1
WHERE NOT EXISTS (SELECT * FROM table2
WHERE table2.column1 = table1.column1);
For more info: https://dev.mysql.com/doc/refman/5.7/en/exists-and-not-exists-subqueries.html
The code below searches my mysql database and comes back with postcodes like IG6,RM11,RM8,RM4,RM2,RM6,RM7,RM1,RM5 and a distance using a stored procedure. (All ok)
PROBLEM: With these results, I want to search another table in same database that may have job information with those Postcodes (probably using LIKE).
What's the best way to get this working? I have tried many examples (implode, arrays, etc)
Is one connection to database correct? How do I query the variable as it does come back with 2 columns, postcode and Distance. Should I split in an array (how?)
END PRODUCT: HGV Driver RM5, Cleaner RM5, Teacher RM5
(SELECT title FROM jobinfo WHERE location IN results from other query);
<?php
include ("conn.php");
$first="RM5";
$result = mysql_query("select outcode, GetDistance(Lat, Lon, (SELECT Lat from postcodes where outcode = '$first' limit 1),(SELECT Lon from postcodes where outcode = '$first' limit 1)) as Distance from postcodes having Distance < 3 order by Distance DESC;");
while($row = mysql_fetch_array($result))
{
echo ($row['outcode']) ;
}
// This returns postcodes
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($results[outcode]) ");
while($row = mysql_fetch_array($resultb))
{
echo ($row['title']) ;
}
mysql_close($con);
?>
Please help.....any reference to join table needs full explanation as all so far don't help!
First Prepare the output into the clause:
in the first while loop:
while($row = mysql_fetch_array($result))
{
$array[] = $row['outcode'] ;
}
Then prepare the array for the IN clause:
foreach ($array as $a) {$clause.= "'$a',";}
$clause=substr($clause,0,-1)
Finally use the clause for the IN statement:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE location IN ($clause) "
===== EDIT === LIKE statement
For like.. you need multiple like statement OR together.. Using SQL LIKE and IN together
Change the prepare clause code to this:
foreach ($array as $a) {$clause.= " location LIKE '%$a%' OR";}
$clause=substr($clause,0,-3)
AND the sql becomes:
$resultb = mysql_query("SELECT title FROM jobinfo WHERE $clause ");
Of course you will want to addin some more error checking.. think of the possible injection.
I think you're trying to do something like this answer MySQL LIKE IN()?
Also, please use parametrized queries How can I prevent SQL injection in PHP?
Suppose i have 1kk records in my database.
Now i need to select some data, and also i need to know how many fields did i select, so my question is:
Is it better to run one query to count data like this:
SELECT COUNT("id") from table where something = 'something'
And after that run one more querio for selection like this:
SELECT 'some_field' from table where something = 'something';
Or Maybe it's better to just select data and then just count it with php like:
count($rows);
Or maybe there is even better ways to do it, for example do it all in one query?
Reading between the lines, I think what your are probably after is SQL_CALC_FOUND_ROWS. This allows you to select part of a result set (using a LIMIT clause), and still calculate the total number of matching rows in a single operation. You still use two queries, but the actual search operation in the data only happens once:
// First get the results you want...
$result = mysql_query("
SELECT SQL_CALC_FOUND_ROWS
FROM `table`
WHERE `something` = 'something'
LIMIT 0, 10
");
// ...now get the total number of results
$numRows = mysql_query("
SELECT FOUND_ROWS()
");
$numRows = mysql_fetch_row($numRows);
$numRows = $numRows[0];
If you fetch all that 1000 records then you can count while you are fetching:
$res=mysql_query("SELECT 'some_field' from table where something = 'something'");
while($r = mysql_fetch_*($res)) {
$count++;
//> Do stuff
}
This way you make only one query and you don't use mysql_num_rows();
One query would be:
SELECT Count(*) AS NumRows, some_field from table
GROUP BY some_field where something = 'something';
Hey guys, I created a list for fixtures.
$result = mysql_query("SELECT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name' GROUP BY date");
$i = 1;
$d = "Start";
while ($row = mysql_fetch_assoc($result))
{
$odate = $row['date'];
$date=date("F j Y", $row['date']);
echo "<p>Fixture $i - $d to $date</p>";
}
As you can see from the query, the date is displayed from the fixtures table.
The way my system works is that when a fixture is "played", it is removed from this table. Therefore when the entire round of fixtures are complete, there wont be any dates for that round in this table. They will be in another table.
Is there anyway I can run an other query for dates at the same time, and display only dates from the fixtures table if there isnt a date in the results table?
"SELECT * FROM ".TBL_CONF_RESULTS."
WHERE compid = '$_GET[id]' && type2 = '2' ORDER BY date"
That would be the second query!
EDIT FROM HERE ONWARDS...
Is there anyway I can select the date from two tables and then only use one if there are matches. Then use the rows of dates (GROUPED BY) to populate my query? Is that possible?
It sounds like you want to UNION the two result sets, akin to the following:
SELECT f.date FROM tbl_fixtures f
WHERE f.compname = '$comp_name'
UNION SELECT r.date FROM tbl_conf_results r
WHERE r.compid = '$_GET[id]' AND r.type2 = '2'
GROUP BY date
This should select f.date and add rows from r.date that aren't already in the result set (at least this is the behaviour with T-SQL). Apparently it may not scale well, but there are many blogs on that (search: UNION T-SQL).
From the notes on this page:
//performs the query
$result = mysql_query(...);
$num_rows = mysql_num_rows($result);
//if query result is empty, returns NULL, otherwise,
//returns an array containing the selected fields and their values
if($num_rows == NULL)
{
// Do the other query
}
else
{
// Do your stuff as now
}
WHERE compid = '$_GET[id]' presents an oportunity for SQL Injection.
Are TBL_FIXTURES and TBL_CONF_RESULTS supposed to read $TBL_FIXTURES and $TBL_CONF_RESULTS?
ChrisF has the solution!
One other thing you might think about is whether it is necessary to do a delete and move to another table. A common way to solve this type of challenge is to include a status field for each record, then rather than just querying for "all" you query for all where status = "x". For example, 1 might be "staging", 2 might be "in use", 3 might be "used" or "archived" In your example, rather than deleting the field and "moving" the record to another table (which would also have to happen in the foreach loop, one would assume) you could simply update the status field to the next status.
So, you'd eliminate the need for an additional table, remove one additional database hit per record, and theoretically improve the performance of your application.
Seems like what you want is a UNION query.
$q1 = "SELECT DISTINCT date FROM ".TBL_FIXTURES." WHERE compname = '$comp_name'";
$q2 = "SELECT DISTINCT date FROM ".TBL_CONF_RESULTS.
"WHERE compid = '$_GET[id]' && type2 = '2'";
$q = "($q1) UNION DISTINCT ($q2) ORDER BY date";