Nest while statements while retaining values from parent PHP mysql - php

Update 2013/12/23
In other words, I have two tables within one database.
If a category exists in one table (e.g.: 43 in featured table) and also exists in another table (43 in category table) then match category ID relevant to the name and if true do something (e.g.: echo).
As far as I can tell nesting an if statement within an if statement that perform two separate MySQL queries doesn't allow me to keep the values of the parent if statement.
I need to somehow store the parent values from the MySQL value so they can be retrieved within the child if statement.
------------------------------
If the category ID in my category_description table exists in another table called sales_promotion then I want to execute another PHP statement.
After doing some research my code so far looks like this
$con = mysql_connect(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
foreach ($breadcrumbs as $breadcrumb) {
$db_selected = mysql_select_db(DB_USERNAME,$con);
$sql = "SELECT * FROM `sales_promotion` LIMIT 0, 30";
$result = mysql_query($sql,$con);
$sql_categories = "SELECT * FROM `category_description` LIMIT 0, 30";
$result_categories = mysql_query($sql_categories,$con);
$test = mysql_fetch_array($result);
while($row = mysql_fetch_array($result_categories))
{
if (strpos($row['name'],$breadcrumb['text']) !== false) {
echo('<p>Category '.$row['name'].' contains '.$row['category_id'].'</p>');
$category_id = $row['category_id'];
while($row = mysql_fetch_array($result))
{
if (strpos($row['options'],$row['category_id']) !== false) {
echo('<p>Category '.$row['name'].' contains '.$category_id.'</p>');
}
}
}
}
}
mysql_close($con);
Could someone please explain how I can achieve this?

Related

Sorting table created by PHP, can't use query to sort

I have a column I want to sort. Let me explain what the code does first.
As you can see, there are three select statements for and from three different tables(table names are in the code). The first query selects data from the table whereby I assign the retrieved data from the id column to $device_id.
The second query selects data from another table according to the value of $device_id(one value only). This will return multiple Board IDs(multiple values). If rows are returned, a table would be created.
In this table, a third query is executed to check for each board_id in the third table($table_tester_info). If the board_id exists, then it would be displayed. Example: If there are 40 board_id and out of the 40 only 20 returned rows, the rows would be displayed in the table.
Now here's the problem. I want to sort the table according to a column in $table_tester_info(the third table) however, I can only use ORDER BY in the second query. That wouldn't be a problem but I want to sort according to a column in $table_tester_info, not $table_tester_config(the second table).
I'm using jQuery as well but I do not want to use any plugins to sort the DOM elements in HTML unless there is no other way(but I'm sure there are many ways, I just don't know it). I've tried sorting the assoc array(?) $tester_name or rather $final_row['tester_name'] which was assigned to it.
Curerntly my table is not sorted when I add ORDER BY at the third query(which I know is wrong). Any help on this?
<?php
// Define database parameters
DEFINE ('DB_USER' ,'iqwdewqe');
DEFINE ('DB_PASSWORD', 'iqadeaqwe');
DEFINE ('DB_HOST', 'qadewe');
DEFINE ('DB_NAME', 'Tqweqwe');
// Connect to database
#mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect'
.'to Database: '. mysql_error());
#mysql_select_db (DB_NAME) OR die ('Could not select the Database: '. mysql_error());
function searchDevice($device_name, $tester_type)
{
$table_device = "TBL_DEVICE_LIST";
$table_tester_config = "TBL_TESTER_CONFIG";
$table_tester_info = "TBL_TESTER_INFO";
$query_string = "SELECT * FROM $table_device WHERE device = '$device_name'
AND tester_type = '$tester_type'";
$device_result = #mysql_query($query_string) or die (mysql_error());
$device_row = mysql_num_rows($device_result);
if($device_row)
{
$device_row = mysql_fetch_array($device_result);
$device_id = $device_row['id'];
// echo "Device ID: $device_id <br>";
$query_string = "SELECT * FROM $table_tester_config WHERE device_id = '$device_id'";
$config_result = #mysql_query($query_string) or die(mysql_error());
$config_row = mysql_num_rows($config_result);
if($config_row)
{
while($config_row = mysql_fetch_assoc($config_result))
{
$board_id = $config_row['board_id'];
$oboard = $config_row['configuration'];
//echo "Board ID: $board_id <br>";
//Query to check if board_id exists,
if exists then display value in while loop
$query_string = "SELECT * FROM $table_tester_info
WHERE board_id = '$board_id' ORDER BY tester_name";
$final_result = #mysql_query($query_string) or die(mysql_error());
$final_row = mysql_num_rows($final_result);
if($final_row)
{
echo "<table border='1'>";
echo "<tr>
<th>Board ID</th>
<th>Tester Name</th>
<th>Board Name</th>
<th>Configuration</th>
<th>Log Created</th>
<th>New</th>
</tr>";
while($final_row = mysql_fetch_assoc($final_result))
{
$board_id = $final_row['board_id'];
$tester_name = $final_row['tester_name'];
$board_name = $final_row['board_name'];
$config = $final_row['config'];
$log_created = $final_row['log_created'];
echo "<tr>
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$oboard</td>
</tr>";
}
}
}
echo "</table>";
}
}
else
{
echo "No Device Name: $device_name with Tester Type: $tester_type.";
}
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="search")
{
$device_name = rtrim($_REQUEST['device_name']);
$tester_type = rtrim($_REQUEST['tester_type']);
echo searchDevice($device_name, $tester_type);
}
?>
Combine queries 2 and 3 with a join. By using an inner join you only get a row if the join is successful.
ie:
select tti.*
from $table_tester_config ttc
inner join $table_tester_info tti
on tti.board_id = ttc.board_id
where td.device = '$device_name' and td.tester_type = '$tester_type'
order by tti.tester_name
Then loop through those results.
Thank you Jack and Chris for giving me the idea. The exact one that I needed is actually(I hard coded the data):
SELECT ti.*
FROM TBL_TESTER_INFO ti
INNER JOIN TBL_TESTER_CONFIG tc
ON ti.board_id = tc.board_id
INNER JOIN TBL_DEVICE_LIST dl
ON dl.id = tc.device_id
WHERE dl.device = '53262'
AND dl.tester_type = 'UFLEX'
ORDER BY tester_name ASC;

How to Compare Huge Array to Database (with PHP or SQL)

I have a big 2D array (576,000 X 4), and huge database (millions records and 10 columns, its size is in Gigabytes). The array, of course, is much smaller than the number of records in the database.
I need some effective way to compare the 2D array to the database, and delete the equal lines from the 2D array only.
Does anyone have an idea how could i apply it efficiently? The speed is very important to me.
I tried to apply it like that:
$query = mysqli_query($config, "SELECT * FROM sec ") or die(mysql_error());
while ($row = mysqli_fetch_array($query) ) {
if ( isset($arr[$row['CHROM']][$row['POS']]) ) {
// delete line from the 2D array
}
}
But, i don't know how efficient it is, because i tried it just on small database, and it makes me load all the records of the database to the PHP page, and it creates a memory problem.
Another way that i check is this:
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
But, its not a good solution, because it took too much time.
edit:
my sec table looks like that:
the call to a item from the 2D array looks like that $arr[some_CHAROM][some_POS]
if the some_CHAROM equal to some CHAROM in the database AND some_POS equal to the POS in the same line, we have a match.
i build the 2D array from a file that the user upload to the website. and im not load it to the mySql.
The algorithm:
convert the file uploaded by the user into a CSV file (if not already in this format); this is a simple task that can be done in several lines of PHP code; see function fputcsv();
create a buffer table: tbl1;
use LOAD DATA LOCAL INFILE to load the content of the (local) CSV file into the buffer table tbl1;
use:
DELETE tbl1
FROM tbl1
INNER JOIN tbl2 on tbl1.id = tbl2.id
to delete from table tbl1 the rows that have matches in table tbl2. I assumed the match field is named id on both tables; change it to match your design;
fetch the data from table tbl1, format it as you wish, send it to the browser;
cleanup: DROP TABLE tbl1;
Because the script processes a file uploaded by an user, in order to avoid any concurrency issue you need to generate for the buffer table an unique name for each user. You can use a prefix and append the userId to it to avoid two users using the same table on the same time.
Try following code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "drupal7";
mysql_connect($servername, $username, $password );
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database1=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database1[$row[0]]=$num_rows;
}
// }
}
echo '<pre>';
print_r($database1);
mysql_free_result($result);
// mysql_close();
$dbname='drupal71';
mysql_select_db($dbname);
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$database2=array();
while ($row = mysql_fetch_row($result)) {
$result1 = mysql_query("SELECT * FROM ".$row[0]);
if(mysql_num_rows($result1)){
$num_rows = mysql_num_rows($result1);
// echo "Table: {$row[0]} ==>".$num_rows."<br>";
$database2[$row[0]]=$num_rows;
}
// }
}
print_r($database2);
$test = array_diff($database1, $database2);
print_r($test);die;
From your code snippet
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$query = mysqli_query($config, "SELECT * FROM sec WHERE CHROM='$chr' && POS='$pos' ") or die(mysql_error());
if (mysqli_num_rows($query) > 0) {
// delete line from the 2D array
}
}
}
I assume, that you want to delete based on $chr and $pos.
So, you could do the following: Assemble a single query to rule them all* :)
$ors = array();
foreach ($arr as $chr=>$v) {
foreach ($v as $pos=>$val) {
$ors[] = "CHROM='$chr' AND POS='$pos'";
}
}
$deleteConditions = "(" . implode(") OR (", $ors) . ")":
$query = mysqli_query($config, "DELETE FROM sec WHERE " . $deleteConditions);
Untested, but this should give you a single query, like
DELETE FROM
sec
WHERE
(CHROM='1' AND POS='2') OR
(CHROM='3' AND POS='4') OR
(CHROM='5' AND POS='6') OR
...
depending on what $chr and $pos are.
*As Ollie Jones noted in the comments: Take care of the overall query length. If required, create a second, third, ... query until you processed all items in appropriate batches.

Multiple SELECT Statements and INSERTS in 1 file

I'm working with a file and I'm attempting to do multiple select statements one after another and insert some values. So far the insert and the select I've got working together but when attempting to get the last SELECT to work I get no value. Checking the SQL query in workbench and everything works fine. Here's the code:
$id = "SELECT idaccount FROM `animator`.`account` WHERE email = '$Email'";
$result = mysqli_query($dbc, $id) or die("Error: ".mysqli_error($dbc));
while($row = mysqli_fetch_array($result))
{
echo $row[0];
$insert_into_user = "INSERT INTO `animator`.`user` (idaccount) VALUES ('$row[0]')";
}
$select_userid = "SELECT iduser FROM `animator`.`user` WHERE iduser = '$row[0]'";
$results = mysqli_query($dbc, $select_userid) or die("Error: ".mysqli_error($dbc));
while($rows = mysqli_fetch_array($results))
{
echo $rows[0];
}
I do not want to use $mysqli->multi_query because of previous problems I ran into. Any suggestions? And yes I know the naming conventions are close naming... They will be changed shortly.
Your code makes no sense. You repeatedly build/re-build the $insert_int-User query, and then NEVER actually execute the query. The $select_userid query will use only the LAST retrieved $row[0] value from the first query. Since that last "row" will be a boolean FALSE to signify that no more data is available $row[0] will actually be trying to de-reference that boolean FALSE as an array.
Since you're effectively only doing 2 select queries (or at least trying to), why not re-write as a single two-value joined query?
SELECT iduser, idaccount
FROM account
LEFT JOIN user ON user.iduser=account.idaccount
WHERE email='$Email';
I'm not sure what you're trying to do in your code exactly but that a look at this...
// create select statement to get all accounts where email=$Email from animator.account
$id_query = "SELECT idaccount FROM animator.account WHERE email = '$Email'";
echo $id_query."\n";
// run select statement for email=$mail
$select_results = mysqli_query($dbc, $id_query) or die("Error: ".mysqli_error($dbc));
// if we got some rows back from the database...
if ($select_results!==false)
{
$row_count = 0;
// loop through all results
while($row = mysqli_fetch_array($result))
{
$idaccount = $row[0];
echo "\n\n-- Row #$row_count --------------------------------------------\n";
echo $idaccount."\n";
// create insert statement for this idaccount
$insert_into_user = "INSERT INTO animator.user (idaccount) VALUES ('$idaccount')";
echo $insert_into_user."\n";
// run insert statement for this idaccount
$insert_results = mysqli_query($dbc, $insert_into_user) or die("Error: ".mysqli_error($dbc));
// if our insert statement worked...
if ($insert_results!==false)
{
// Returns the auto generated id used in the last query
$last_inisert_id = mysqli_insert_id($dbc);
echo $last_inisert_id."\n";
}
else
{
echo "insert statement did not work.\n";
}
$row_count++;
}
}
// we didn't get any rows back from the DB for email=$Email
else
{
echo "select query returned no results...? \n";
}

PHP - Insert SQL on while loop

I generated a random monster team from a table, and limited by 6. Now, I also want to insert the team into user_team which contains the fields
m1,m2,m3,m4,m5,m6
Those represent Monster 1 to Monster 6. Now when I try to insert the generated monsters into the team, only the last Monster seems to be inserting into it while I all of my monsters to be inserted.
http://prntscr.com/8zrj2
$sql = "SELECT * from monsterdata ORDER BY RAND() LIMIT 6";
$result = mysql_query($sql);
// this checks if you have a result
if ($result == null) echo "No result";
else {
while (($row = mysql_fetch_array($result)) != false) {
$row = mysql_fetch_array($result);
{
// html code here
}
}
the Insert statement is
$monster = $row['id'];
$sql = "INSERT into user_team(m1,m2,m3,m4,m5,m6) VALUES('$monster','$monster','$monster','$monster','$monster','$monster')";
$result = mysql_query($sql);
Just don't know where/how to place it so it inserts the right values into the right columns.
If it were me, I would push the ids into an array and then use that like so:
$monsterIds = array();
while(($row = mysql_fetch_array($result)) !== false) {
$monsterIds[] = $row['id'];
}
mysql_query("INSERT INTO user_team (m1, m2, m3, m4, m5, m6) VALUES ('{$monsterIds[0]}', '{$monsterIds[2]}', '{$monsterIds[3]}', '{$monsterIds[4]}', '{$monsterIds[5]}')") or die(mysql_error());
Also, don't forget to use the triple equals when comparing row results so that you don't get caught by a weird bug where things evaluate to false that aren't actually false (=== is the way to go with many functions which might return either an array, integer, or a boolean depending on the outcome).
The values will be placed in the columns in the order they are supplied.
Here is my example using PDO (php library):
$DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $username, $password);
$webContractList=$DBH->query('SELECT id,nume,data FROM user2')->fetchAll();
$STH=$DBH->prepare("INSERT INTO user (id,nume,data) VALUES (:id ,:nume , :data)");
foreach ($webContractList as $item){
$STH->execute(array(':id'=>$item['id'],
':nume'=>$item['nume'],
':data'=>date('Y-m-d',strtotime($item['data']))));
}

Why isn't this script working? (odd/even)

I've been writing a script to display the names of users based on whether they are assigned an even or odd comment id. It calls up data from 2 different tables in the same database. Here is the table information:
Table 'comments' has the columns commentid, tutorialid, name, date: Table 'winners' has the columns pool, pool2, pool3, pool4, pool5, pool6, pool7. Table 'comments' has multiple rows that are updated through user input. Table 'winners' has only 1 row with numbers that are randomly generated daily.
The first part of the script that displays "Result 1" and "Result 2" is working properly. The part that isn't working is the part that calls up the usernames. I only want to display the usernames that corralate with the result that is displayed IE if Result 1 is chosen then I only want the usernames with even 'commentid's displayed.
<?php
$db = mysql_connect('localhost', 'username', 'pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
if ($row['pool'] % 2) {
echo "<h4>Result 1</h4>";
$names = get_names(1);
foreach($names as $name) {
echo $name . "<br/>";
}
} else {
echo "<h4>Result 2</h4>";
$names = get_names(0);
foreach($names as $name) {
echo $name . "<br/>";
}
}
function get_names($pool_result)
{
$name_array = array();
$query = "SELECT * FROM comments where mod('commentid',2) = $pool_result";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
array_push($name_array, $row['name']);
}
return $name_array;
}
?>
Can anyone figure out why this isn't working?
The SELECT statement with the mod is not referencing the field. Should be backticks instead of single quotes. Single quotes indicate a string constant, which would result in a constant result set (mod('commentid',2) appears to have a result of 0). It should be something like this:
$query = "SELECT * FROM comments where mod(`commentid`,2) = $pool_result";
Adding quotes around commentid treats it as a string, and you can't mod a string by an integer. Try the following instead:
$query = "SELECT * FROM comments WHERE commentid % 2 = $pool_result";
This was taken from the following Stack question: select row if the "value" % 2 = 1. MOD()

Categories