check array values exist in mysql table - php

I need to check the array values which contains more than 400 values which is existing in the MySQL table where i should get result for all the values which I am passing even if it not exist in the column.
for example:
cont table
----------
Column1
---------
9xxxxxxxxx
91xxxxxxxx
92xxxxxxxx
my array contains 9xxxxxxxxx & 91xxxxxxxx. How can i iterate to get the column exist or not.
I tried with foreach and building query
$sql = 'SELECT cont WHERE num IN(';
foreach($jsonString as $val){
$sql = $sql . "'$val', ";
echo $val;
}
if(mysqli_query($con,$sql)){
echo "exist";
}else {
echo "error";
}
Is there any efficient way other than the above which is faster in time?

First of all if cont is your table name than where is FROM keyword.
If cont is column name than where is TABLE name?
As per your question, you have 400+ ids, than why are you using loop here? you can simply use implode() with comma seperated values, like
<?php
$ids = implode(",",$jsonString);
$sql = "SELECT * FROM cont WHERE num IN ($ids)"; // assuming cont is table name
?>
In your loop you will get the "," in last iteration at the end this will break your query.

Related

looping through rows of a mysql table with non sequential index

I have a MySQL table that looks like this
index (auto incremented)
data
type
1
a1
1
3
a2
1
4
b62
3
9
m52
1
and i loop through it with this code
for($i=1; $i<= number of rows; $i++){
$query = "SELECT * FROM messagesforinstructor where type='1' and index='$i'";
$result = mysqli_query($db, $query);
$display=mysqli_fetch_assoc($result);
echo $display['data'];
}
but as you can see that it would fail cause the auto incremented indexes are not sequential.so at i=2 it would fail without making it to i=3.
any idea how to make it select the next index in the table
Simple solution
Don't use * use specified column names
Use one query to retrieve the entire result set
Use OOP approach and save yourself having to repeat code (you don't neeed to change the connection but you can:
// From...
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
// To...
$db = new mysqli($db_host,$db_user,$db_pass,$db_name)
I assume that type is an integer field; no need to use quotation marks in the query
Code
// Run the query to select the messages
$sql = "SELECT data FROM messagesforinstructor WHERE type = 1";
$query = $db->query($sql);
// Option 1
// Loop though result set with a foreach loop
foreach ($query as $message) {
echo $message[0];
}
// Option 2
// Loop through the result set with a while loop
while ($message = $query->fetch_assoc()) {
echo $message["data"];
}

How can I echo out all values associated with the email in my table

I have a table with several columns. A user logs in with a unique email and imputs values which are in turn stored in the mysql table. How can I echo out all these values associated with the user's email? I have tried a for loop, using the table ID values, which works when you increment through consercutive values, which isn't the case with the table.
//Here's my code so far:
$rownum = "SELECT * FROM tablename";
$rowrun = mysql_query($rownum, $connect); // simply querying here
//$connect is the link to server nd database.
$rowcount=mysql_num_rows($rowrun);//getting. number of table rows, to be used in forloop
for($c=1; $c<=$rowcount; $c++){
//$c will be the stand-in for ID values from the table. which I'm using to loop.
$query = "SELECT * FROM tablename WHERE. emai='$email'; //all users will be identified by email
$row = mysql_fetch_array($rowrun); //getting array. of associated column values
$grades = $row['grades'];
$classroom = $row['classroom'];
$ID= $row['ID'];
if(!empty($grades)&&!empty($classroom)){
echo "learner from class".$classroom."has. gotten".$grade."%"
//here I want all display grades and classsroom. number obtained from the mysql table associated with user's email
}
}
?>
Here's the problem: the loop works when I have an initial value for $c and the values are consercutive. But the values on the table won't be arranged consercutively and hence the loop won't increment desirably ( $c++). Whats more, the initial ID (primary auto incrementing column) value will keep changing depending on the user.
What are my options here? Foreach loop? While loop? Select by group?
To print or echo out all values associated with the user's login email
Can't you just run one query:
$sql = "SELECT * FROM table_name WHERE email = '$email'"
This will return all matches, and then you can run this query and loop through the returned data (if any)
$resultset = $conn->query($sql);
if ($resultset->num_rows > 0) {
// echo data
} else {
// no data returned
}

select user id from a table, using results of an array in php

I have a table called users(user_id, name, surname). In my php code a get an array with values like that:
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
$like_users = $e['user'];
$array[]=$like_users;
}
$arstring = implode(' ',$array);
?>
I want to select surname and name from table users, that their user_id is equal to those numbers exists as values in $array. Any idea how to do this?
Try this query
$sql='select name,surname from user where user_id in(?,?.....?)'
The number of ? is equal to the length of the array.
Then use
$query=$con->prepare($sql);
$query->execute($array);
Then fetch the returned rows.
PS:Creating prepared statements with variable number of arguments have been asked before on SO and the method is same as I have described.
collect all user_ids from SQL Query in one Array, then compare this array with your existing array
<?php
$array = array();
while($e = mysql_fetch_array($favorites)){
// $e['user'] equal user_id
$array[$user_id]= $e['user'];
}
?>
we use $array[$user_id] to save each user_id to corresponding array index, then compare two array as you want

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Dynamically assign alias to all the field names in msyql query

I have 2 tables in mysll DB. Both tables have few fixed and few dynamic columns (Fields / Schema). I want to join both these tables with following query:
SELECT *
FROM `cd` cd
LEFT JOIN cd_n cn ON cd.id = cn.fk_cd
And I want to result as
CD_Column1 CD_Column1 CD_Column3 ...... CN_Column1 CN_Column2 CN_Column3 .....
value value value ...... value value value ...
value value value ...... value value value ...
Where ..... is dynamic column names of both the tables.
So the case is I dont know the column names because they are dynamic and I want rename (alias) it on query level. Please let me know how can I do this?
You would need to query the information_schema to get the column names of that two tables. Lets assume You would have the cd column names stored in the array $cd_columns and the cd_n column names in the array $cdn_columns.
Then in PHP when creating the query loop through the column arrays and do something like this:
$sql = 'SELECT ';
// add the cd columns
$i = 0;
foreach($cd_columns as $col) {
$sql .= "{$col} AS CD_Column{$i},";
$i++;
}
// add the cd_n columns
$i = 0;
foreach($cdn_columns as $col) {
$sql .= "{$col} AS CN_Column{$i},";
$i++;
}
// remove the trailing comma
$sql = trim($sql, ',');
// continue the SQL
$sql .= ' FROM ...';
Was this helpful?

Categories