set variable to field name of sql query - php

My goal here is to set a variable to a field name from a mysql query. Some pseudo code below
1. $query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321';"
2. $result = mysql_query($result);
3. $while($row = mysql_fetch_assoc($result)){
4. $column1 = name_of_column($row['firstName']);
5. }
6. echo $column1
//Would return the string
firstName
obviously line 4 being the real pseudo part

Is this what you're after?
$query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321';"
$result = mysql_query($result);
$all_results = array();
$while($row = mysql_fetch_assoc($result)) {
$formatted_row = array();
foreach ( $row as $column => $value ) {
$formatted_row[] = array($column, $value);
}
$all_results[] = $formatted_row;
}
Or just use $column and $value how you like inside the foreach loop.
Or do you want specifically the first column, which can be accessed with reset($row); $first_key = key($row);?

You want to name a variable with the name of the column?
$$row['firstName'] = $row['firstName'];
Another way is like this:
$query = "SELECT firstName, lastName FROM users WHERE userName = 'mhopkins321'";
$result = mysql_query($result);
$row = mysql_fetch_assoc($result);
foreach($r as $key=>$value){
$$key = $value;
}
Now you can echo the values out by their column name.

This sounds redundant, but you could always use array_search:
while($row = mysql_fetch_assoc($result)){
$value = $row['firstName'];
$key = array_search($value, $row);
}
See more on array_search.

Related

How to merge an array inside another array in php?

Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php

Working with foreach, issets, arrays?

What is the best practise to move for multiple foreach statements to an array? I am repeating the process in my code, when I know there is a better and faster way to do this. Is it possible to isset the foreach? I am starting to work with PDO, how would I shorten my below code or move it into an array of some type?
if (isset($_POST['one'], $_POST['two'], $_POST['three'])) {
foreach($_POST['one'] as $id => $one) {
$sql = "UPDATE table SET one = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($one, $id));
}
foreach($_POST['two'] as $id => $two) {
$sql = "UPDATE table SET two = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($two, $id));
}
foreach($_POST['three'] as $id => $three) {
$sql = "UPDATE table SET three = ? WHERE id = ?";
$q = $db->prepare($sql);
$q->execute(array($three, $id));
}
}
EDIT: An example of the HTML/PHP (input type='text') for a more clear example:
$stmt = $db->query('SELECT * FROM table ORDER BY id ');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "
<input type='text' id='one' value='{$row['one']}' name = 'one[{$row['id']}]' />
<input type='text' id='two' value='{$row['two']}' name = 'two[{$row['id']}]' />
<input type='text' id='three' value='{$row['three']}' name = 'three[{$row['id']}]' />";
}
Assuming all the inputs will have the same IDs:
$sql = "UPDATE table set one = :one, two = :two, three = :three where id = :id";
$q = $db->prepare($sql);
$q->bindParam(':one', $one);
$q->bindParam(':two', $two);
$q->bindParam(':three', $three);
$q->bindParam(':id', $id);
foreach ($_POST['one'] as $id => $one) {
$two = $_POST['two'][$id];
$three = $_POST['three'][$id];
$q->execute();
}
You should only prepare the statement once, not every time through the loop. And by using bindParam you can bind all the parameters to variable references. You can then set all the variables in one loop, and execute the query with those values.
Another way to do this:
<?PHP
foreach($_POST as $name => $value) {
if(isset($name,$value)){
$sql = "UPDATE table SET $name = $value WHERE id = $name";
$q->execute($db->prepare($sql));
}
}
?>
If you're posting other information too, you can move this into an array. Then have
foreach($_POST[fieldsToUpdate] as $name => $value) {
Let me know if you have further questions.

PHP MySQL Get column names While iterating through all records

$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
//How to echo column names and values here?
}
Is it possible to echo a table's column names and values while iterating through the entire table in a while loop?
You can use foreach loop
$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
foreach($row as $key => $value) {
print "$key = $value <br />";
}
}
$query = mysql_query("SELECT * FROM mytable");
while ($row = mysql_fetch_assoc($query)) {
print_r($row);
}
try this.. column_name is the same name u used in the table
echo $row['column_name'];

Print same values once in a while loop

$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$name = $fetch['name'];
echo "$name";
}
In my example, after echoing out $name in a while, the values are:
Carrots
Lemon
Carrots
Lemon
Is there a way to not repeat printing the same value that will look like this:
Carrots
Lemon
Thank you very much.
$query = mysql_query("SELECT DISTINCT name FROM tblname");
while($fetch =mysql_fetch_array($query)) {
echo $fetch['name'];
}
SQL Solution:
SELECT DISTINCT `name` FROM tblname;
or
SELECT `name` FROM tblname GROUP BY `name`;
PHP Solution:
$my_array = array();
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$my_array[] = $fetch['name'];
}
$my_array = array_unique($my_array);
echo implode('<br />', $my_array);
$names = array();
$query = mysql_query("SELECT * FROM tblname");
while($fetch =mysql_fetch_array($query)) {
$name = $fetch['name'];
if (!in_array($name,$names)){
echo "$name";
$names[] = $name;
}
}
Will work.
$sql = mysql_query("SELECT DISTINCT table1.id, table2.id, table2.name
FROM table1, table2 WHERE id=id GROUP BY name");
This Will Work 100% sure.
SET GROUP BY name and DISTINCT. If not it is not working.
Simply append them into an array like:
$items[] = $item;
After that do:
$items = array_unique($items);
After that, simply print the items.
You can fetch them all into an array and then run array_unique()
$query = mysql_query("SELECT * FROM tblname");
$arr = array();
while($fetch =mysql_fetch_array($query)) {
$arr[] = $fetch;
}
$output = array_unique($arr);
foreach ($output as $uniqe_val) {
echo $unique_val;
}
I find the question ambiguous. I think you're asking for what appears in How to make a list of unique items from a column w/ repeats in PHP SQL

Checking for empty fields in mysql table

I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...

Categories