Select every item in a SQL column into an array, PHP - php

I've hit a little wall in something I'm trying to do.
I have a table, entitled 'projects', in a database in SQL.
My issue is that I can't seem to select every row in a specific column.
This is the code that I've got so far relevant to this question (keep in mind that '$conn' is the connection to the SQL database, and the include command on the second line is just to include that connection):
//CONNECTION FILE
include "../include/dbh-inc.php";
//ASSIGNING QUERY VALUES TO VARIABLES
$q1 = mysqli_query($conn,"SELECT pid FROM projects;");
$q2 = mysqli_query($conn,"SELECT ptitle FROM projects;");
$q3 = mysqli_query($conn,"SELECT plink FROM projects;");
//SETTING ARRAYS FROM VARIABLES
$ids = mysqli_fetch_array($q1);
$titles = mysqli_fetch_array($q2);
$links = mysqli_fetch_array($q3);
mysqli_close($conn);
file_put_contents("newtest.txt","$titles\n");
foreach($titles as $title) {
file_put_contents("newtest.txt","$title\n", FILE_APPEND); //Testing
}
if(count($ids) > 0) {
file_put_contents("TEST.txt","");
for($i = 0; $i < count($ids)-1; $i+=1) {
$count = count($ids);
$title = $titles[$i];
$id = $ids[$i];
$link = $links[$i];
file_put_contents("TEST.txt","$i: $title, $id ($count), $link\n",FILE_APPEND);
echo("
<div class=\"projlink\">
<a href=\"$link\" style=\"width:190px;height:90px\">
<h2>$title</h2>
</a>
</div>
");
}
}
else {
echo("
<h2>Nothing here currently!<br>Be patient!</h2>
");
}
Any thoughts?
Thanks!
- Raphael

You are only fetching one row with mysqli_fetch_array. Also, you can get all columns in one query:
$q1 = mysqli_query($conn,"SELECT pid, ptitle, plink FROM projects;");
$rows = mysqli_fetch_all($q1, MYSQLI_ASSOC);
If you don't have mysqli_fetch_all then:
while($rows[] = mysqli_fetch_assoc($q1));
Then just loop $rows and use the columns:
foreach($rows as $row) {
echo $row['pid'] . ' ' . $row['ptitle'] . ' ' . $row['plink'];
}
If you really need separate arrays (this is rarely necessary):
$ids = array_column($rows, 'pid');
$titles = array_column($rows, 'ptitle');
$links = array_column($rows, 'plink');

Related

How do I separate output from database?

I tried to get multiple rows out from my database with PHP but all I get is one line of text like: "8910"
My code is following:
$sql = "SELECT * FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$rows = mysqli_num_rows($sth);
for ($x = 0; $x <= $rows; $x++) {
$sql = "SELECT idPosts FROM posts WHERE idUsers=$id";
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
$postId = $result['idPosts'];
echo $postId;
}
And then I edit this: echo $postId." ";
And get a space between the id's like this: 8 9 10.
I tried to do $postIds = explode(" ", $postId);
And then echoing out for example $postIds[0] but I get all the id's once again
Now I do not know what to do so I need help ^^
Replace $postId = $result['idPosts']; with $postId[] = $result['idPosts'];. That way you create an array an you can just access it like $postId[0].
You also forgot to query again.
...
$sql = "SELECT idPosts FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if(!$sth) {
...
Your second query is unnecessary, you already have all the data from your first query. Just replace your code with this:
$sql = "SELECT * FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if (!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$postIds = array();
while ($row = mysqli_fetch_array($sth)) {
$postIds[] = $result['idPosts'];
}
After this loop you will have an array of all the idPosts values. You can then process them as you need to. Or you can process them in the loop:
while ($row = mysqli_fetch_array($sth)) {
$postId = $result['idPosts'];
// code to process postId e.g.
echo "$postId<br/>";
}

Search multiple row separate by comma from mysql using php

It is a tracking system like DHL. Tracking shipment number from MySQL database using php form.
but I need it Search multiple row separate by comma from mysql using php.
<?php
$ship=$_POST['Consignment'];
$cons = explode(',',$ship);
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no = '$cons[]'";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Shipment Name: <?php echo $ship_name; ?>
Shipment Phone: <?php echo $phone; ?>
<?php }//while
}//if
else {
echo 'In else....';
?>
Consignment Number not found.Search Again.
<?php
}//else
?>
So I need my search will work with separating by comma(,).
Thanks for helping me.
You can use IN operator in that case.
<?php
$ship=$_POST['Consignment'];
?>
<?php
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";
$result = dbQuery($sql);
$no = dbNumRows($result);
if($no == 1){
while($data = dbFetchAssoc($result)) {
extract($data);
?>
Hope it will help to you.
change your sql query you have written '$cons[]' in select query which is wrong . after explode you will get data as 1,2,3 so you just need to write variable in query not array and user IN Operator like this.
`$sql = "SELECT * FROM tbl_courier WHERE cons_no IN(".$ship.")";`
You should always prepare/sanitize the POST data before using it in MySql query (in terms of security):
<?php
if (isset[$_POST['Consignment']] && !empty($_POST['Consignment'])) {
$ship = $_POST['Consignment'];
$cons = explode(',', $ship);
$cons = array_filter($cons, function($v){
return trim(strip_tags($v));
});
$cons = '"' . implode('","', $cons) . '"';
$sql = "SELECT * FROM tbl_courier WHERE cons_no IN ($cons)";
$result = dbQuery($sql);
$no = dbNumRows($result);
if ($no == 1) {
while ($data = dbFetchAssoc($result)) {
extract($data);
....
}
....
}
?>
Please Use Find IN SET
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'1,2,3,4,5')
Updated
SELECT * FROM tbl_courier WHERE FIND_IN_SET(cons_no,'$ship')
Note :- $ship Comma Separated Value not an array
I found the Answer:
if(isset($_POST['Consignment'])){
$ship=$_POST['Consignment'];
$shipment= explode(',',$_POST['Consignment']);
$ship = implode("', '",$shipment) ;
$query = "SELECT * FROM `tbl_courier` WHERE `cons_no` IN('$ship')";
$results = $mysqli->query($query);
if($results){
print '<table border="1">';
while($row = $results->fetch_assoc()) {
print '<tr>';
print '<td>'.$row["cons_no"].'</td>';
print '<td>'.$row["customerName"].'</td>';
print '<td>'.$row["customerPhone"].'</td>';
print '</tr>';
}
print '</table>';
// Frees the memory associated with a result
$results->free();
}
else {
echo "Query Not Match";
}
$mysqli->close();
}
Thanks to Answer.

Repeating SQL insert statement in loop till id has certain value?

<?php
include ("db.php");
$id2 = "SELECT MAX(id) FROM osalejad;";
$id = $conn->query($id2);
if (id<= 8){
while($id<= 7) {
$min = 1;
$max = 20;
$suvanumber = rand($min, $max);
$bar = (string) $suvanumber;
$prii= "vaba2" . $bar;
$sql="INSERT INTO osalejad (name) VALUES ('$prii')";
$result = $conn->query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
}
else {
echo '8 osalejat on juba kirjas';
}
?>
I have a question, i want to insert data into MYSQl table, word with a random number, but problem is, it never work as it should - if i have 3 records in name column, then till, it adds 8 more records, instead of 5 records. Is something outside of scope atm?
I will use the DB in this code.
<?php
include("db.php");
$sql = "SELECT * FROM `osalejad`;";
$result = $conn->query($sql);
$var = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = mysqli_fetch_array($result)) {
$var[] = $row["name"];
}
} else {
/// echo "0 results";
}
//shuffle the array, and encode into json.
shuffle($var);
$brack=json_encode($var);
$testbrack= json_encode(array_chunk($var,2));
$final = '{';
$final .= '"teams":';
$final .= $testbrack;
$final .= ',"results":[[[[0,0],[null,null]],[[null,null],[null,null]]]]}';
//updating last tournament bracket.
$sql1 = "UPDATE lan_brackets SET json='$final' ORDER BY tid DESC LIMIT 1;";
$roundOne=$conn->query($sql1);
?>

php while loop only displays one result for a mysql query across multiple tables

I am having an issue with a while statement only returning one result. this is my first time trying to display product information from several tables and I don't know what I'm doing wrong. here is the code:
<?php
require('./includes/config.inc.php');
require(MYSQL);
$sql = sprintf("SELECT * FROM tea");
$res = mysqli_query($dbc, $sql);
if(!$res){
die('Could not complete query: '.mysqli_error($dbc));
} else {
echo 'Success!<br />';
while($row = mysqli_fetch_array($res)){
$table = $row['category'];
$inum = $row['item_number'];
echo $table.' '.$inum.'<br />';
$fetch = sprintf("SELECT sub_category, item_name, description FROM $table WHERE item_number ='$inum'");
$fetchRes = mysqli_query($dbc, $fetch);
if(!$fetchRes){
die('Could not fetch: '.mysqli_error($dbc));
} else {
while($fetchRow = mysqli_fetch_array($fetchRes)){
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
echo $id.' '.$subCat.' '.$iNumber.' '.$iname.' '.$desc.'<br />';
}
}
}
}
Inside your while loop, you should be using the $fetchRow variable as the array from which to grab columns, such as 'sub_category'.
IS
$subCat = $fetchRes['sub_category'];
$iNumber = $inum;
$iname = $fetchRes['item_name'];
$desc = $fetchRes['description'];
Needs to be: Res to Row
$subCat = $fetchRow['sub_category'];
$iNumber = $inum;
$iname = $fetchRow['item_name'];
$desc = $fetchRow['description'];

Store Column Values in Array

I'm trying to store the title(summary) and date(created) of an event in an array. But I think im missing something in my loop.
<?php
$summary = array();
$date = array();
mysql_connect('mysql.server', 'myUsername', 'myPass') or die('Could not connect: ' . mysql_error());
mysql_select_db("mxgsite") or die(mysql_error());
$query_summary = mysql_query('SELECT summary FROM event_info') or die(mysql_error());
$query_date = mysql_query('SELECT created FROM event_details') or die(mysql_error());
$row_summary = mysql_fetch_array($query_summary);
$row_date = mysql_fetch_array($query_date);
$i = 0;
while(($row1 = mysql_fetch_array($query_summary))) {
$row2 = mysql_fetch_array($query_date);
$summary[] = $row['summary'];
$date[] = $row['created'];
echo $summary[$i] . " " . $date[$i] . "<br ?>";
$i++;
}
I know i'm getting values because I can echo out 1 value, but if I want to put all the values in an array and try to echo out that array I keep getting blank values?
It seems to me like you are trying to do too many things here. Since the 2 sets of values are not being stored in a way where they are related/linked to each other, you might as well deal with them in separate while loops. Try something like this:
while ($row = mysql_fetch_array($query_summary)){
$summary[] = $row[0];
}
while ($row = mysql_fetch_array($query_date)){
$date[] = $row[0];
}
If you want to relate the tables, per the comments above, you can try something more like:
$result = mysql_query('SELECT a.eventid, a.summary, b.created
FROM event_info a
join event_details b
on a.eventid = b.eventid');
$events = array();
while ($row = mysql_fetch_array($result)){
$event = array();
foreach ($row as $key=>$value){
$event[$key]=$value;
}
$events[] = $event;
}

Categories