Here i have made an MySQL which has the columns of "id","name","username","email",age" . Where even i made the the PHP code to retrieve the data for the given id.
eg:if the user enter id=3 then it shows the datas corresponding to the id.
But now i want set multiple inputs so that user can type more than one id and it list the corresponding datas of the particular id.
My PHP Code:
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
require_once('dbConnect.php');
$sql = "SELECT * FROM user WHERE id='".$id."'";
$r = mysqli_query($con,$sql);
$result = array();
while($res = mysqli_fetch_array($r)){
array_push($result,array(
"id"=>$res['id'],
"name"=>$res['name'],
"username"=>$res['username'],
"email"=>$res['email'],
"age"=>$res['age']
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
Now this URL gives the perfect result:
"http://www.allwaysready.16mb.com/Sort.php?id=4"
Now how can i get the corresponding values for the multiple id's?
You can use array syntax to pass multiple IDs to your script and use MySQL's IN() to query against them all at once.
URL: http://www.allwaysready.16mb.com/Sort.php?id[]=4&id[]1&id[]=2
$ids = $_GET['id'];
$ids = array_map(function($id) {
return (int) $id;
}, $ids);
$ids = implode(',', $ids);
$sql = "SELECT * FROM user WHERE work IN($ids);
I cast the IDs to integers because your current code is wide open to SQL injection. You really should be using paramterized queries.
Use the "IN" condition:
If id is a number:
SELECT * FROM user WHERE id IN (89, 25);
If id is a string, put the id's in quotes:
SELECT * FROM user WHERE id IN ('89N', '15B', '25E');
Rewrite your query in PHP to use the In Query condition, paying close attention to your column definition data types. Strings must be quoted for example.
Related
This is my table:
All I want to do is to obtain the '75' int value from the 'expquim' column to later addition that number into another (75+25) and do an UPDATE to that camp (now it is 100).
Foremost, there are dozens of ways to accomplish what you want to do. If you're querying the table, iterating over results and doing some conditional checks, the following will work for you. This is pseudo code... Check out the function names and what parameters they require. $db is your mysqli connection string. Obviously replace tablename with the name of your table. The query is designed to only select values that are equal to 75. Modify the query to obtain whatever results you want to update.
This should get you close to where you want to be.
$query = "SELECT * FROM tablename WHERE idus='1'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
if($row['expquim'] == 75){
$query2 = "UPDATE tablename SET expquim='".$row['expquim']+25."' WHERE idus='".$row['idus']."' LIMIT 1 ";
$result2 = mysqli_query($db,$query2);
}
}
im doing something where users has a local database and when he clicks to checks new books, it get all the IDS(fixed) form his local database and create String separeted by comma (1,2,3,4,5) and then do a GET to my server
www.myserver.com/getNews?ids=1,2,4,10
and in the server side i do this:
1) Get the last ID(fixed) and set in a var called $total
2) get the IDS send by the user and create a array using .explode(",")
3) get the missing values $missing = array_diff(range(1,$total),$ids);
get max id and get the missing numbers between the $total and $ids
and here come the part that i think its heavy:
for each $missing value i do a select and build a array to display as json
foreach($missing as $m) {
$sql = "SELECT * FROM `books` WHERE id='$m'";
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = array_map('utf8_encode', $row);
}
}
echo json_encode($emparray);
this is the only one approach or is there any other more light function?
you can try this way. Implode your array with comma then use NOT IN condition in your query to select all books you want.
$strMissing = implode(',', $missing);
$sql = "SELECT * FROM `books` WHERE id NOT IN (".$strMissing.")";
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];
}
}
if i have a category page that im rendering by querying the subcategories in my database, then if i click on one of the subcategories it sends me to
mydomain.com/product_list.php?id=subcategory.
is there a way take the subcategory from the url to query the database to only show the products in that subcategory?
i think it'll look something like:
$sql = mysql_query("SELECT * FROM products");
This can be obtained from $_GET DOCs.
$subcategory_id = $_GET['id'];
So this would become:
if(array_key_exists('id', $_GET) and is_numeric($_GET['id'])) {
$subcategory_id = (int) $_GET['id'];
$SQL = "SELECT * FROM products WHERE subcategory_id = $subcategory_id";
}
Note I have cast the input variable to an integer to prevent SQL injection etc. As the ID must always be a number.
If you need to pass in a string then use mysql_real_escape_string() DOCs on it first and don't type cast to an integer (int):
if(array_key_exists('id', $_GET)) {
$subcategory_id = mysql_real_escape_string($_GET['id']);
$SQL = "SELECT * FROM products WHERE subcategory_id = '$subcategory_id'";
}
$query = mysql_query("SELECT * FROM `products` WHERE `id` = " . mysql_real_escape_string($_GET['id']);
Of course, that's assuming the table name is products, and the ID columns is id.
Your question is a little confusing. I think to start some tutorials on PHP should be looked at, and the different types of http requests.
What you are looking at is called a GET request. You can access all key, value pairs after the ? in a url through the superglobal $_GET this is an associate array containing all key => values.
So as per above $_GET['id'] is the value you want. But please before you begin look at SQL injection, it is too easy to think that that value can be used directly to make a query.
I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:
$id = array(1,4,7,3,11,120); // The array containing the ids
$query = mysql_query("SELECT *
FROM posts
WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
I think you want the IN clause:
$idList = implode(",", $id);
SELECT *
FROM posts
WHERE id IN ( $idList );
The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.
Standard Disclaimer/Warning:
As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.
Use PHP's implode function to convert the array into a comma separated value string.
Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:
$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);
$query = sprintf("SELECT *
FROM posts
WHERE id IN (%s)",
mysql_real_escape_string($csv));
$result = mysql_query($query)
I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL. If the id values were strings, each would have to be encapsulated inside of single quotes.
What you want is SQL's IN clause.
SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)
In PHP, you'll probably want something like:
$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));
Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:
$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");
And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.