MySQL contains variable - php

I have an array in PHP that is looping through a set of names (and a corresponding quantity). I would like to print the ones found in a MYSQL database table (to which I've succesfully connected). I'm currently using the code:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
echo $quan." ".$row['name']. "\n";
}
}
For some reason, this only prints the last quantity and name in the array. Help?
For example, if the array has key-value pairs of {A-4, B-2, C-3}, and table contains {A, B, D} as names ... it'll only print "2 B".

Change the code to the following:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
You have to loop through the result. By the way, stop using mysql_query()! use MySQLi or PDO instead ( and be careful of SQL Injection ; you can use mysqli_real_escape_string() to handle input parameters ). For MySQLi implementation , here it is :
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
And rather "\n", I prefer using PHP_EOL ( as shown above )
And as the comment suggests, the SQL statement can be executed once, as follow:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
e.g. in $arr contains "peter", "mary", "ken", the Query will be:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
sidenote: but I don't understand your query. You only obtain the name back from the query? You can check number of rows, or you can even group by name, such as:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
to get what you want.
UPDATE (again): based on the comment of OP, here is the solution :
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
The above query will show the name appearing in the table only. Names not in table will not be shown. Now full codes ( be cautious of SQL Injection , again )

Related

How to calculate the sum of number array elements from multiple database rows using php?

I need to count the number of elements that exist in the column of a MySQL database row for multiple rows and them add them all together. This is the code I used to count the number of array elements (which are numbers separated by commas):
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
But now I need to do this for each row, which could vary depending on the query. I need to add the $result of each row together to get a final sum of all the rows. I used the following code but I get the incorrect value, can someone please point me in the right direction?
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
foreach ($count_fetch as $row) {
$result = substr_count($count_fetch['micro_analysis'], ",") + 1;
$end_result += $result;
}
echo $end_result;
You are just fetching 1 row and then trying to count over that row, instead you need to loop over the rows and add the fields in that...
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$end_result = 0;
$count_query = mysqli_query($conn, $sql);
while( $row = mysqli_fetch_assoc($count_query)) {
$end_result += substr_count($row['micro_analysis'], ",") + 1;
}
echo $end_result;
Replace your code with the following:
$sql = "SELECT * FROM samples_database WHERE order_id = $order_id";
$count_query = mysqli_query($conn, $sql);
$count_fetch = mysqli_fetch_assoc($count_query);
$end_result=0;//initialize variable to 0
foreach ($count_fetch as $k => $row) {
if($k == 'micro_analysis'){
$result = substr_count($row, ",") + 1; //change over here
$end_result += $result;
}
}
echo $end_result;

mysql query array counter

Apologies if I have the terminology wrong.
I have a for loop in php which operates a mysql query...
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
}
The results that are given when I insert a...
print_r ($job_results);
On screen -> Array()
If I change the query from $user_id_pc[$i] to $user_id_pc[14] for example I receive one set of results.
If I include this code after the query and inside the for loop
echo $i;
echo $user_id_pc[$i] . "<br>";
I receive the number the counter $i is on followed by the data inside the array for that counter position.
I am not sure why the array $job_results is empty from the query using the counter $i but not if I enter the number manually?
Is it a special character I need to escape?
The full code
<?php
print_r ($user_id_pc);
//Select all columns to see if user has a profile
$query = "SELECT * FROM user_profile WHERE user_id = '" . $_SESSION['user_id'] . "'";
//If the user has an empty profile direct them to the home page
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 0)
{
echo '<br><div class="alert alert-warning" role="alert"><h3>Your appear not to be logged on please visit the home page to log on or register. <em>Thank you.</em></h3></div>';
}
//Select data from user and asign them to variables
else
{
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$cw_job_name = $row['job_description'];
$cw_rate = $row['hourly_rate'];
$job_mileage = $row['mileage'];
$job_postcode = $row['postcode'];
$response_id = $row['user_profile_id'];
}
}
for ($i = 0; $i <count($user_id_pc); $i++)
{
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
$job_data = mysqli_query($dbc, $query2);
$job_results = array();
while ($row = mysqli_fetch_array($job_data))
{
array_push($job_results, $row);
}
echo $i;
?>
<br>
<?php
}
print ($query2);
print $user_id_pc[$i];
?>
This is primarily a syntax error, the correct syntax should be:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '{$user_id_pc[$i]}'";
Note that this is correct syntax but still wrong!! For two reasons the first is that it's almost always better (faster, more efficient, takes less resources) to do a join or a subquery or a simple IN(array) type query rather than to loop and query multiple times.
The second issue is that passing parameters in this manner leave your vulnerable to sql injection. You should use prepared statements.
The correct way
if(count($user_id_pc)) {
$stmt = mysqli_stmt_prepare(" SELECT job_title, job_info FROM job_description WHERE postcode_ss = ?");
mysqli_stmt_bind_param($stmt, "s", "'" . implode("','",$user_id_pc) . "'");
mysqli_stmt_execute($stmt);
}
Note that the for loop has been replaced by a simple if
You have to check the query variable, instead of:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '$user_id_pc[$i]'"
have you tried this:
$query2 = " SELECT job_title, job_info FROM job_description WHERE postcode_ss = '" . $user_id_pc[$i] . "' ";
And another thing, try something different like this:
while ($row = mysqli_fetch_array($job_data))
{
$job_results[] = array("job_title" => $row["job_title"], "job_info" => $row["job_info");
}
Then try to print the values.
Sorry but I like foreach(), so your working code is:
<?php
// To store the result
$job_results = [];
foreach($user_id_pc as $id ){
// selecting matching rows
$query2 ="SELECT job_title, job_info FROM job_description WHERE postcode_ss = '".$id."'";
$job_data = mysqli_query($dbc, $query2);
// checking if query fetch any result
if(mysqli_num_rows($job_data)){
// fetching the result
while ($row = mysqli_fetch_array($job_data)){
// storing resulting row
$job_results[] = $row;
}
}
}
// to print the result
var_dump($job_results);

echo all and entire MySQL Query rows in php without specifically naming each column

I have
$result = "";
if(someCondition)
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
else
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
$result could have 0 -> infinity rows returned
Table 1 and Table 2 have different amounts of columns with different names
I want to write 1 generic loop after the above else that will just print out all of the rows. Preferably 1 per line or deliminated.
To clarify, one of the two query calls will fill the $results variable with rows.
I wont know which one fills it at run time so I want to just do a print all contents to screen. Is there a method that does this? is there a fast loop that iterates through all of the rows without explicitly saying the column names?
bored enough to answer:
$result = "";
if(someCondition){
$result = mysql_query("SELECT * FROM table1 WHERE column = '$value' ");
}else{
$result = mysql_query("SELECT * FROM table2 WHERE column = '$value' ");
}
while ($row = mysql_fetch_array($result)) ) {
foreach($row as $key => $var)
{
echo $key . ' = ' . $var . '<br />';
}
}

How to pull columns with '1' in MySQL

I was wondering if there was an easy way to do this:
I have a user_id column and then 33 other columns with either a '0' or a '1' as the type. How can I easily select all of the columns where the user_id = 320 and the column's data equals 1?
The column titles are labeled 1-33. In the end I want to join it to another table where 1-33 is the id to a label column.
Does this make sense?
Thanks for any help!
Try this I get all the fields and test if it BIT and then inject it to the query
And please tell me the result
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result){
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0){
$str ="";
$nums = mysql_num_rows($result);
$i = 0 ;
while ($row = mysql_fetch_assoc($result)){
$i++;
if($row['Type'] = 'BIT' && $i != $nums){
$str .= " WHERE `".$row['Field']."` = 1 AND";
}
elseif($row['Type'] = 'BIT' && $i == $nums){
$str .= " WHERE `".$row['Field']."` = 1 ";
}
}
}
$query = "SELECT * FROM mytable user_id = 320 AND ".$str;
$q = mysql_query($query);
This is for the first part of you question
the second part the same operation
and this working without knowing the fields name

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