Select multiple rows from database - php

I want to be able to select all rows where a value matches with the one I'm calling for in php
This is what I have for now and the only thing I get is the first row. Not the other rows.
<?php>
session_start();
require "db.inc.php";
$id = $_SESSION['userId'];
$sql = "SELECT followingId FROM following WHERE followerId=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
echo var_dump($result);
$followedId = $result['followingId'];
echo $followedId;
And $conn is the connection variable in db.inc.php

You must iterate through the results array you are fetching
while ($row = mysqli_fetch_array($result)) {
foreach($row as $field => $value) {
//do something with $field and $val
}
}

Related

How am I supposed to store a value from my database as a variable in php using PHP and SQL?

I would like to see where my code is incorrect. I want to store values from my database as a php array. Then I'd like to store the individual parts of the array as separate variables. Here is my code:
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = mysqli_fetch_row($result);
$comment0 = $comments[0];
$comment1 = $comments[1];
$comment2 = $comments[2];
$comment3 = $comments[3];
$comment4 = $comments[4];
$comment5 = $comments[5];
$comment6 = $comments[6];
$comment7 = $comments[7];
$comment8 = $comments[8];
$comment9 = $comments[9];
?>
This will run your mysql query and add each comment to an array of comments, then print the array.
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = array();
while($comment = mysqli_fetch_row($result)){
$comments[] = $comment;
}
print_r($comments);
?>
not sure if you are in console or through web server.
<?php
$result = mysqli_query($db, "SELECT column FROM table");
if (!$result) {
echo 'Could not run query';
exit;
}
$comments = mysqli_fetch_row($result);
foreach($comments as $comment){
echo print_r($comment,1).'--------------\r\n<br>\r\n';
}
?>
this is called a loop. loop is your friend.

How to display multiple array value in PHP?

I am having an trouble in displaying values in PHP.
Value pass through URL career.php?mode=1,2,3
Here is my code
$id = $_GET['mode']; // Id get from URL
//echo $id;
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";
$res = mysqli_query($conn, $query);
foreach(($row = mysqli_fetch_array($res)) as $key1){
$key[] = $key1;
}
PHP Code:
<?php echo $key;?>
Hence it is in looping so it shows the last looped value. Is it possible to display the all values through loop.
Help me out guys!!
You have multiple options to output an array.
Echo and foreach
You c an loop through your array and echo each $key and $value
foreach ($keys as $key => $value) {
echo $key." : ".$value."<br />";
}
print_r and var_dump
This is mostly used in debugging.
print_r($keys);
var_dump($keys);
Imploding
You can implode your array to echo the concatted values.
// The first parameter is the devider or separator
echo implode('', $keys);
Is it possible to display more than one value from the column?
Yes, ofcourse. Look at the following example:
foreach ($keys as $value) {
echo $value['columnone'];
echo $value['columntwo'];
echo $value['columnthree'];
}
Resources
implode() - PHP Manual
print_r() - PHP Manual
var_dump() - PHP Manual
foreach - PHP Manual
As your code in open for sql injection you need to use bind and prepare statement . Use while loop to echo your data as
$ids[] = $_GET['mode']; // store it into array
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN (";
$query .= implode(',', array_fill(0, count($ids), '?'));// bind your param
$query .= ') ';
$stmt = $conn->prepare($query);
call_user_func_array(array($stmt, 'bind_param'), $ids);//Call a callback with an array of parameters
$stmt->execute();
$stmt->bind_result($job_title);// bind result
while ($stmt->fetch()) {// use wlile loop here
printf("%s\n", $job_title);//echo result
}
You can do something like this:
$mysqli = new mysqli("server", "user", "password", "db");
$id = $_GET['mode'];
$query = "SELECT `job_title` FROM `job` WHERE `job_id` IN ($id)";
if($res = $mysqli->query($query)){
while($obj = $result->fetch_object()){
echo $obj->job_title;
}
}
$res->close();
Try this:
<?
$servername = "localhost";
$username = "yourUSERNAME";
$password = "yourPASS";
$dbname = "yourDBNAME";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
exit();}
$id = $_GET['mode']; // Id get from URL
//echo $id;
$query = "SELECT `job_title` FROM `job` WHERE `job_id`=".$id."";
$result = $conn->query($sql);
while($row=$result->fetch_assoc()){
//do something...
}
$conn ->close();
?>
tip: put your connection on another connection.php file.
like:
require('Connect.php');
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
}

Values stored multiple times into array

I am trying to save values from my database into an array, this works however it shows some of the values multiple times some of them 2 and other ones 3 times.
<?php
$conn = mysqli_connect("127.0.0.1", "root", "", "testdb");
$sql = ("SELECT * FROM vraag");
$result = $conn->query($sql);
// run query
$query = mysqli_query($conn, $sql);
// set array
$array = array();
// look through query
while($row = mysqli_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['vraag']; // etc
}
while ($row = mysqli_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo $columnData;
}
}
?>

PHP: filtering mysql_query result for specific column?

Is there a quick way to filter a mysql_query result to get a list containing only values of a specific column?
$query = mysql_query("SELECT * FROM users");
$list_of_user_names = get_values($query,"names");
What is the name of the function to be used in place of get_values?
Assuming your field name in databse is "names"
$query = mysql_query("SELECT names FROM users");
while($row = mysql_fetch_assoc($query)){
echo $row['names'];
echo "<br>";
}
NOTE : mysql_* functions are deprecated in new version of php, use mysqli_* or PDO
Use below function.
function get_values($q,$c)
{
$arr = array();
while($row = mysql_fetch_array($q))
{
$arr[] = $row[$c];
}
return $arr; // return all names value.
}
Try this:
$query = mysql_query("SELECT names FROM users");
if (!$query) {
echo "Could not successfully run query from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $names
while ($row = mysql_fetch_assoc($query)) {
echo $row["names"];
}

check table from my sql query

Hello I'm checking duplicated data from tables. I have a problem that from where data selected. My code is:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (".$select[$i].") WHERE location=('".$id."')";
$result = mysql_query($SQL);
$cs=$d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'],$sub_cat)) {
$sub_cat[]= $db_field['sub_cat'];
$cs++;
$d=$cs;
$d--;
}
}
}
I need to know that sub_cat selected from which $select[i]. How to find it?
To get the values, do this:
$sub_cat = array();
$select = array("core_network","daisy_chain", "rf_bts", "rf_power", "rf_transmission");
$d='0';
for ($i=0;$i<=4;$i++){
$SQL = "SELECT sub_cat FROM (" . $select[$i] . ") WHERE location=('".$id."')";
$result = mysql_query($SQL); // deprecated - use PDO
$cs = $d;
if ($result) {
while ($db_field = mysql_fetch_array($result)) {
if(!in_array($db_field['sub_cat'], $sub_cat)) {
$table = $select[$i];
$sub_cat[$table][] = $db_field['sub_cat'];
// I have no clue what's going on here in your example:
$cs++;
$d=$cs;
$d--;
}
}
}
}
Then, to retrieve it:
foreach ($sub_cat as $table_name => $values) {
foreach ($values as $row) {
// output values here
}
}

Categories