PHP mySQL JOIN with matching column names - php

Noticed a rather large problem. When I join two tables togeter the fact that there is a column called ID in both of them causes the wrong tables ID to be used in a PHP equasion later on.
The simple solution would be to change the column name, but there are other standards thoughout the database too including columns called name in every table and title in many of them.
Is there a way around this or should I rename the entire database to ensure that there are no duplicate columns.
THE CODE FOR REFERENCE
$criteria = "SELECT *
FROM voting_intention,electors
WHERE voting_intention.elector = electors.ID
AND electors.postal_vote = 1
AND voting_intention.date = (select MAX(date)
from voting_intention vote2
where voting_intention.elector = vote2.elector)
AND electors.telephone > 0"
function get_elector_phone($criteria){
$the_elector = mysql_query("SELECT * $criteria"); while($row = mysql_fetch_array($the_elector)) {
return $row['ID']; }

While "Gunnx" solution is perfectly acceptable, I'd like to present an alternative since you appear to be using only the ID column of the result.
SELECT
electors.ID
FROM
voting_intention,electors
....

I wrote this function to assist in doing this. Basically it prepends the table name to the fields name of an associated array.
while($row = mysql_fetch_array($the_elector))
{
return $row['ID'];
}
would become
while($row = mysql_fetch_table_assoc($the_elector))
{
return $row['voting_intention.ID'];
}
function:
function mysql_fetch_table_assoc($resource)
{
// function to get all data from a query, without over-writing the same field
// by using the table name and the field name as the index
// get data first
$data=mysql_fetch_row($resource);
if(!$data) return $data; // end of data
// get field info
$fields=array();
$index=0;
$num_fields=mysql_num_fields($resource);
while($index<$num_fields)
{
$meta=mysql_fetch_field($resource, $index);
if(!$meta)
{
// if no field info then just use index number by default
$fields[$index]=$index;
}
else
{
$fields[$index]='';
// deal with field aliases - ie no table name ( SELECT T_1.a AS temp, 3 AS bob )
if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
// deal with raw data - ie no field name ( SELECT 1, MAX(index) )
if(!empty($meta->name)) $fields[$index].=$meta->name; else $fields[$index].=$index;
}
$index++;
}
$assoc_data=array_combine($fields, $data);
return $assoc_data;
}
?>

mysql_fetch_row will get the data as a numerical array

Related

Detect when id retrieved from php query is changed

I'm running a query where I'm getting the average score of a student, by getting the average score of an activity type(quiz,exams,etc.) and multiplying it to its assigned grade percentage(ex: 80 *.03).
I've grouped the result by its activity_ID and Student ID.
To get the Grade of the student I need to add the score of each activity type. by simple adding all the result of each activity type.
(ex:grade =10.40+30+12;)
Now my problem is when the student ID is changed the result of the previous student is added to the result of the new one.
(ex:new student grade = previous result, plus his own)
I want to detect when the Student ID is changed inside the
while($row = mysqli_fetch_array($result)) {
$studentID_link = $row['studentID'];
$atName = $row['AT_name'];
$GLOBALS['AR_Score'] = $row['AVG(AR.Score)'];
$AT_gradePercentage =$row['AT_gradePercentage'];
$AT_gradePercentage /=100;
$periodGrades = $AR_Score*$AT_gradePercentage;
$variableName = $variableName + $periodGrades;
}
Use
mysqli_fetch_assoc()
Check for the id after storing the initial student id in a temp variable outside of the loop. Compare each new row's student ID to the previously stored temporary id. Also declare an array outside of the loop and use
array_push()
to push each total onto the array. Use an associative array with the student ID as the key and avoid using array_push if you are accessing student IDs out of order or use an index in mysql to allieviate this issue.
Honestly, you may want to reexamine your sql or show us if you want us to rewrite the code for you.
Update:
If the current mysqli_fetch_array is fetching an associative array, you can leave it, however refer to my above suggestions if you are having issues with that.
$curr_student = NULL;
$array = [];
while($row = mysqli_fetch_array($result)) {
$studentID_link = $row['studentID'];
if($curr_student === NULL || $curr_student !== $studentID_link){
$curr_student = $studentID_link;
if(!array_key_exists($curr_student, $array)) $array[$curr_student] = 0;
}
$atName = $row['AT_name'];
$GLOBALS['AR_Score'] = $row['AVG(AR.Score)'];
$AT_gradePercentage =$row['AT_gradePercentage'];
$AT_gradePercentage /=100;
$periodGrades = $AR_Score*$AT_gradePercentage;
$array[$curr_student] = $array[$curr_student] + $periodGrades;
}
I'm not certain about your global array and how you are using it, but this should work to add your students into each array member regardless of random access of student ID.

Trying to get a page to populate data from a database

I'm trying to write a script that gets data from a sql server based on the id of the entry in my data base. when I try to access the page using the link with the id of the entry it returns as if it does not recognize the id. Below is the php code :
<?php
require('includes/config.inc.php');
require_once(MYSQL);
$aid = FALSE;
if (isset($_GET['aid']) && filter_var($_GET['aid'], FILTER_VALIDATE_INT, array('min_range' => 1)) ) {
$aid = $_GET['aid'];
$q = "SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft USING(aircraft_id) WHERE aircraft_id = $aid";
$r = mysqli_query($dbc, $q);
if (!(mysqli_num_rows($r) > 0)) {
$aid = FALSE;
}
}// end isset tid
if ($aid) {
while ($acdata = mysqli_fetch_array($r, MYSQLI_ASSOC)){
echo'<h2>'. $acdata['tail_number'] .'</h2>';
}
} else {
echo '<p>This pages was accessed in error.</p>';
}
?>
Any hints?
Try to var_dump($q); before $r = mysqli_query($dbc, $q); to inspect your query and then just execute it through phphmyadmin or in MySQL server terminal directly and see what does it return.
Update:
Use var_dump($q);die(); to stop script from executing after dumping.
You are using a field alias in your query, so you must use that in your echo to:
echo'<h2>'. $acdata['tn'] .'</h2>';
Get rid of the USING(aircraft_id), it causes an error and your query doesn't execute.
"SELECT aircraft_id, aircraft_name AS name, aircraft_type AS type, tail_number AS tn FROM aircraft WHERE aircraft_id = $aid"
I guess it's a leftover from a previous version of the query? Using (id) is a shortcut for
FROM
foo
INNER JOIN bar ON foo.id = bar.id
It can be used when the tables to be joined are joined on columns which have the same name. Just shorter to write.
Since you are not joining you have to remove it.

PHP - SQL select first column with no data

How do I find the first column with no data?
//column pet1='dog'
//column pet2=''
//column pet3=''
//column pet4='cat'
if($F=="getempty"){
$uid=$_GET["uid"];
$sql = mysql_query("SELECT DISTINCT pet1,pet2,pet3,pet4 FROM a WHERE uid='".$uid."' AND pet1='' OR pet2='' OR pet3=''OR pet4=''");
while($column=mysql_fetch_field($sql)){
$empty=$column->name;
echo json_encode(array("empty"=>$empty));
}
}else{}
I keep trying but so far it just returns all column names if one is empty
pet1,pet2,pet3,pet4
DISTINCT will combine the rows which are exactly alike (having all the selected columns the same) and return them.
To get the name of the first empty column, use a query like:
SELECT
CASE
WHEN pet1 = '' THEN 'pet1'
WHEN pet2 = '' THEN 'pet2'
WHEN pet3 = '' THEN 'pet3'
WHEN pet4 = '' THEN 'pet4'
ELSE NULL
END AS firstempty
FROM a
WHERE uid = '$uid';
The idea is that the CASE statement checks each one in order, and finding an empty one returns the column name without checking the rest of them.
Don't forget to escape $uid with mysql_real_escape_string() before passing it to the query.
$uid = mysql_real_escape_string($uid);
Since we're now getting the column name inside a field called firstempty, we'll also need to change the way it's fetched:
while($row = mysql_fetch_assoc($sql)){
$empty = $row['firstempty'];
echo json_encode(array("empty"=>$empty));
}

Possibly simple PHP/MYSQL issue with retrieving and showing data

I have been racking my brains over this for a while now. Here is the data I have in the SQL data base as an example:
ID | TYPE | DATA
1 | TXT | TEST
2 | PHP | php
3 | JS | JAVASCRIPT
That is just an example, there are multiple listing for TXT, PHP and JS throughout the table. What I want to do is retrive all the data and display it all into separate drop down/select boxes. Meaning, select box one would list all data with type TXT, select box two would list all data with type PHP and select box 3 would list all data with type JS. The only way I have came about doing this is doing individual sql queries for each different type. I know there is a way to do it all in 1 query and then display it the way I want to but I just can't seem to figure out how and I know its going to drive me nuts when someone helps and I see just how they did it.
The only way that I know of to get all of the data in one query is just to do a generic SELECT * FROM tbl, and then you can group them in the code:
$res = mysqli_query('SELECT * FROM tbl');
$data = array();
while($row = mysql_fetch_assoc($res)) {
$type = $row['type'];
$data[$type][] = $row;
}
// $data contains all of the record, grouped by the TYPE column
foreach($data as $type => $records) {
echo "records for $type: <select>";
foreach($records as $record) {
echo "<option value='$id'>$id</option>";
}
echo "</select>";
}
Just retrieve all records and loop through them using PHP. Use an iterator if the recordset is going to be huge to prevent using too much memory.
$lists = array();
foreach($recordset as $record) {
$lists[$record['type']][$record['id']] = $record['data'];
}
Know you have an array containing all data.
Just order it by Type and make a loop using "foreach" into the results, changing of select box when the type is different than the preivous.
In this way you only loop once over the array.
You can do kind of grouping with "ORDER BY TYPE":
SELECT id, data
FROM table
ORDER BY type;
Then, in data output loop you can track current type, and build another select box once type changed:
$currentType = "no type";
while($row = mysql_fetch_assoc($res)) {
if ($currentType != $row['type']) {
$currentType = $row['type'];
// start new select box here
}
// do some other work here
}
BTW, such approach looks like kind of hack :)

How to manipulate parameter according to other parameter in a php function?

I have id names with the second part of table name plus id.
For example
admins_id in omc_admins table,
customers_id in omc_customers table,
products_id in omc_products table,
categories_id in omc_categories table etc.
Now the following function code is supposed to find orphans. For example, when I delete categories, it will check the products and find orphans of that category.
Now I am not sure how to manipulate parameter according to other parameter. For example 'id' in $this->db->select('id,name');.
id will be changing according to the $db_table.
function checkOrphans($segment, $id, $db_table){
$data = array();
$this->db->select('id,name');
$this->db->where($id,id_clean($segment));
$Q = $this->db->get($db_table);
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
I think I can use $db_table. For example $db_table is omc_categories, I can use categories part and add to id.
categories_id.
Can anyone tell me how to do it please?
I am using codeigniter, but question is purely php.
You can get the id name in this way:
$id_name = preg_replace('/.*_(.*)/', '${1}_id', $db_table);
then
$this->db->select($id_name . ',name');

Categories