How to select rows from array of keys? - php

I have a table and the primary key is 'unique_identifier'. I would like to select the rows from a number of keys. I have an array that contains the keys who's data from the table I would like to select and retrieve all at once. Please set aside security concerns.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier='????????????";
$result = $mysqli -> query($sql);
$count = $result -> num_rows;
if($count > 0){
echo 'count: '.$count;
}else{
echo 'error';
}

You can use implode function of PHP and IN operator of SQL.
$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');
$sql = "SELECT * FROM tracker WHERE unique_identifier in ('" . implode("','", $myArray) ."')";

Suppose you have name, roll, email in a table.After completing your sql that you have done you can access every attribute by this way.
while($row = $result->fetch_assoc()){
$name = $row["name"];
$email = $row["email"];
$roll = $row["roll"];
}

Related

Need Some Help Regarding Fetching Data from Mysql using explode function

In the below script I want to fetch data from mysql using a explode function and also a variable within an explode function.
Here's how I want to get
<?php
include ('config.php');
$track = "1,2,3";
$i = 1
$trackcount = explode(",",$track);
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
This is the code
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
I want sql to fetch data from tracks table where id = $trackcount[$i]
Whatever the value of $trackcount[$i] mysql should fetch but it shows a blank screen.
If I put this
$sql = "SELECT * FROM tracks WHERE id='$trackcount[1]'";
It works perfectly
save your $trackcount[$i] in one variable and then pass it in the query as given below
<?php
include ('config.php');
$track = "1,2,3";
$i = 1;
$trackcount = explode(",",$track);
$id=$trackcount[$i];
$sql = "SELECT * FROM tracks WHERE id='$id'";
$retval = mysql_query($sql, $conn);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['track_name']}";
}
mysql_free_result($retval);
?>
and one more thing check your previous code with echo of your query and see what is passing ok.
echo $sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//like this
problem is with your query
$sql = "SELECT * FROM tracks WHERE id='$trackcount['$i']'";//change
to
$sql = "SELECT * FROM tracks WHERE id='$trackcount[$i]'";
Generally you would want to use the IN operator with this type of query, so for you this would be:-
$sql="SELECT * FROM `tracks` WHERE `id` in (".$track.");";
or, if the $ids are in an array,
$sql="SELECT * FROM `tracks` WHERE `id` in (".implode( ',', $array ) .");";

MYSQL query using a set of values (values stored from a session array) not working

I'm just a beginner and I'm doing a project (a shopping cart). User can add a product to the cart and the id of the product stores in a session. When I use those ids to echo out PRICE from DB it's not working. I'm using PHP & MYSQL. Here is my code
if(count($_SESSION['cart_items'])>0){
// getting the product ids
$nos = "";
foreach($_SESSION['cart_items'] as $no=>$value){
$nos = $nos . $no . ",";
}
// removing the last comma
$nos = rtrim($nos, ',');
//echo $nos; (will display like this INT VALUES 1,2,3,4)
$nos=mysql_real_escape_string($nos);
$site4->DBlogin();
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
$result = mysql_query($qry);
$row = mysql_fetch_assoc($result);
echo $row['price'];
}
PHP is not recursively embeddable:
$qry = "SELECT * FROM vendorproducts WHERE product_no IN('.implode(',',$nos).')";
^---start of string end of string ---^
Since you're already in a string, .implode(...) is just plain text, NOT executable code.
This means your query is illegal/invalid SQL, and if you had even basic/minimal error checking, would have been told about this:
$result = mysql_query($qry) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
I have fixed the issue and thanx MARC for your suggestions.
I was making two mistakes:- IMPLODE input field was not an array. and as Marc said the query was not executable.
Changes made :-
$nos = rtrim($nos, ',');
**$narray = array($nos);**
$fgmembersite4->DBlogin();
$qry = **'SELECT * FROM vendorproducts WHERE product_no IN ('.implode(',',$narray).')'**;
$result = mysql_query($qry) or die(mysql_error());
**while (**$row = mysql_fetch_assoc($result)){
echo $row['price'];}

Sorting PHP arrays

I have three MySQL tables that I need to query for all of the rows. Upon getting all of the rows from each table, I need to create a multidimensional array whereby each index of that array contains only value from each of the tables. What I have right now works. But, something is telling me that there has got to be a better way of accomplishing this.
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $table) {
$sql = "SELECT * FROM ".$table."";
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$num = mysqli_num_rows($query);
$i = 0;
while($row = mysql_fetch_array($query)) {
$id[$i] = $row['user_id'];
$i++;
}
for($i=0;$i<$num;$i++) {
if(!is_array($final[$i])) {
$final[$i] = array($id[$i]);
} else {
array_push($final[$i], $id[$i]);
}
}
}
The end results is something that looks like this
$final = array(array('table_one_row_one_val', 'table_two_row_one_val', 'table_three_row_one_val'),
array('table_one_row_two_val', 'table_two_row_two_val', 'table_three_row_two_val'),
array('table_one_row_three_val', 'table_two_row_three_val', 'table_three_row_three_val')
);
I get the gut felling that this could be done much more effectively, but I'm not sure how.
Thanks,
Lance
You can make your code simpler if you make your query more explicit in selecting the columns you want in the order you want them. So for example:
$sql = 'SELECT table_one.user_id as u1, table_two.user_id as u2, table_three.user_id as u3 FROM ' . implode(',', $tables);
Then each row of your result set will have the columns in the proper order making the construction of your arrays less involved. For example:
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
while($row = mysql_fetch_array($query)) {
$final[] = array($row['u1'], $row['u2'], $row['u3']);
}
There may be issues with the order and relationships of the data in these arrays (especially if all 3 tables don't have the same number of rows), but working just off the information above, this is another way you could approach it. Something to think about anyway.
Try this:
$sql = "SELECT 'user_id' FROM ".$table;
What about:
$tables = array('table_one', 'table_two', 'table_three');
$final = array();
foreach($tables as $tableIndex => $table) {
$sql = "SELECT user_id FROM ".$table;
$query = mysqli_query($con, $sql)or die(mysqli_error($con));
$i = 0;
while($row = mysql_fetch_array($query)) {
$final[$tableIndex][$i] = $row['user_id'];
$i++;
}
}
It is always better selecting only the columns you will use. SELECT * is not a good SQL practice.

PHP/MySQL - Get multiple fields from one entry in a table

I thought I could find loads of examples on how to do this but nothing I find tells me how to get the values in PHP.
Say I have this code:
$query = "SELECT name, age FROM people WHERE id = 2";
$result = mysql_query($query);
How do I get the data from $result?
Pseudo code:
$name = $result['name'];
$age = $result['age'];
Did you try this?
$query = "SELECT name, age FROM people WHERE id = 2";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo $row['name'];
echo $row['age'];
You need to get a row from the result first. You can get a number-based array using mysql-fetch-row or an associative array using mysql-fetch-assoc.
$query = "SELECT name, age FROM people WHERE id = 2";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$name = $row['name'];
$age = $row['age'];
To note: the mysql functions are deprecated. You should use mysqli or PDO instead.

How to display the content of more then one SQL database row

I am trying to retrieve the data stored in an unknown number of mySQL database rows and display them using HTML. At the moment I can display data from one row.
Each row has a unique id number, I was planning to iterate through by comparing this number to the variable counter. But it would then leave me with the issue of displaying the results in HTML. At the moment I am just echoing variables that contain data from the rows. However what I want to create is a HTML list that increases in length depending on how many rows are in the table.
Here is my current PHP code for retrieving a row from the database is:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
$row = $query->fetch_assoc();
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
At the moment I am just displaying some of the results in HTML using this code:
<div id="inner_container">
<?php echo "$task_id $proj_name $task_name $task_deadline"; ?>
</div>
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
while($row = $query->mysqli_fetch_assoc()) {
$task_id = $row["task_id"];
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_importance = $row["task_importance"];
$task_description = $row["task_description"];
$task_deadline = $row["task_deadline"];
$task_members = $row["task_members"];
$task_budget = $row["task_budget"];
echo "$task_id $proj_name $task_name $task_deadline";
}
Since you have built an associative array using fetch_assoc all you need to do is loop through that array. The OO example on http://php.net/manual/en/mysqli-result.fetch-assoc.php should get you what you need. A quick example:
$sql = "SELECT * FROM project_tasks WHERE project_name='$proj_name' AND task_id='$counter'";
$query = mysqli_query($db_conx, $sql);
echo '<div id="inner_container">';
while ($row = $query->fetch_assoc()) {
$proj_name = $row["project_name"];
$task_name = $row["task_name"];
$task_deadline = $row["task_deadline"];
echo "$task_id $proj_name $task_name $task_deadline";
};
/* free result set */
$row->free();
echo '</div>;

Categories