Making multiple mysqli queries using a for loop - php

I'm trying to make a series of mysqli queries by looping through the values of an array - (called column) - but nothing is being returned.
for ($i = 0; $i < sizeof($column); $i++)
{
$mutualInterests = mysqli_query ($conn, "SELECT USER_1 FROM INTERESTS WHERE answer = " . $column[$i] );
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}
}

Just replace your given code with following and see result ..........
$query='SELECT USER_1 FROM INTERESTS WHERE answer ="'.$column[0].'"';
for ($i = 1; $i < sizeof($column); $i++)
{
$query.=' OR answer ="'.$column[$i].'"';
}
$mutualInterests = mysqli_query ($conn,$query);
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}

Replace this:
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo " $row[USER_1]";
}
with this:
$count = 0;
while ($row = mysqli_fetch_array ($mutualInterests))
{
echo $row[$count]."<br>";
$count++;
}
Let me know if it works now! :)

Related

Multiple for-loops from one $result = $conn->query($query)

I have imported data into a table and I am now accessing that data with PHP using the code as follows,
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->close();
$conn->close();
This works!
I am really just curious why adding a second for-loop does not work, unless I declare $result again?
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . 'Flag<br/>';
}
$result->close();
$conn->close();
Doesn't work, although 'Flag' is printed an appropriate number of times.
Whereas if I declare $result again.
<?php
require_once 'connect.php';
$query = "SELECT * FROM JunkData";
$result = $conn->query($query);
if(!$result) die("Fatal Error");
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result = $conn->query($query);
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
$result->close();
$conn->close();
The code does work.
I have tried unsetting a few variables with unset($row) etc and I did notice if I remove the line,
$row = $result->fetch_array(MYSQLI_ASSOC);
from the second for loop, it will print the last value in the Number column as many times as the loop will run.
I hope that is understandable. I am wondering what is happening in the code that I need to re-declare $result if I want to run a second for loop against it.
The standard solution I would recommend is to do fetch_all()
Instead of:
$rows = $result->num_rows;
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
Do
$rows = $result->fetch_all();
foreach ($rows as $row)
{
...
}
// then you can re-loop same array of $rows
foreach ($rows as $row)
{
...
}
There is an internal pointer when you call fetch_* function.
In your first for loop, you send the pointer to the end of the result set.
So, the next fetch will return nothing.
If you run $result->data_seek(0) you will reset this pointer and can reuse:
for ($name = 0; $name < $rows; ++$name)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Name']) . '<br/>';
}
$result->data_seek(0); //<---- REPLACE HERE
for ($number = 0; $number < $rows; ++$number)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo htmlspecialchars($row['Number']) . '<br/>';
}
Of course, usually there is no need to loop the same result set twice, you may need to rethink your logic and loop only once.

possible ?: mysql row to an if condition

hi guys im trying to insert a mysql data to a variable that will set an if condition depending on the result. is this possible, am i doing it right? what is the right way to do it ? what i want to achieve is to validate if there's a equal value given by the user inside my mysql rows.
$db = mysql_connect('localhost','test','');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
$dbname = 'test';
$btest = mysql_select_db($dbname);
if (!$btest)
{
print "<h1>Unable to Select the Database</h1>";
}
$sql_statement = "SELECT * ";
$sql_statement .= "FROM registered_email ";
$result = mysql_query($sql_statement);
$outputDisplay = "";
$myrowcount = 0;
if (!$result) {
$outputDisplay .= "<br /><font color=red>MySQL No: ".mysql_errno();
$outputDisplay .= "<br />MySQL Error: ".mysql_error();
$outputDisplay .= "<br />SQL Statement: ".$sql_statement;
$outputDisplay .= "<br />MySQL Affected Rows: ".mysql_affected_rows()."</font><br />";
}
else{
$numresults = mysql_num_rows($result);
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
}
}
and here what im trying to achieve, btw is $clientEmail has a default values so dont worry about that.
if($clientEmail === $outputDisplay){
...... some codes..........
}
else{
....... some codes.......
}
you can use mysql row to compare with your user input. you can add condition, while you'r getting row value for the email inside the loop.
$email_exist = 0;//define the default value.
for ($i = 0; $i < $numresults; $i++)
{
$row = mysql_fetch_array($result);
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist = 1;
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
why don't you use a while loop?
make sure to update to mysqli_* because mysql_* is deprecated and is going to get removed on php 7.0
$email_exist = 0;//define the default value.
while ( $row = mysql_fetch_assoc($result) ) // you are using associative array and not the indexed once tho you should go for mysql_fetch_assoc
{
$id = $row['id'];
$sentEmailClients = $row['email'];
$outputDisplay.= "".$sentEmailClients."<br />";
//my code start here
if($sentEmailClients == $clientEmail)
$email_exist += 1; //maybe it exist more than once?
}
//outside the loop
if($email_exist == 1) {
//..........write some code.......
}else{
//........write some code.......
}
or you can do something more simple like this
$query = "select email from tablename where email='$clientemail'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count > 0) {
// email exists
} else {
// doesn't exist
}

How to store table Field(column) name into An Array?

This is the my code and I am trying to store the value into the Array.
$result = $cid->query("SHOW COLUMNS FROM commissions");
echo $count = $result->num_rows;
while ($row = $result->fetch_assoc()) {
echo $row['Field'];
echo "<br/>";
}
I am trying to do this $ar[]=$row; but there is nothing display !!
$result = $cid->query("SHOW COLUMNS FROM commissions");
echo $count = $result->num_rows;
while ($row = $result->fetch_assoc()) {
ar[] = $row;
echo "<br/>";
}
for($i = 0, $i<12, $i++) {
echo ar['field'][0];
}
Nothing Display in the output
You can do following way to store column name into array. Read comment after every line
For PDO
$rs = $cid->query('SELECT * FROM commissions');// your query
for ($i = 0; $i < $rs->field_count(); $i++) {/// count nu of column
$col = $rs->fetch_fields()($i);//Returns metadata for a column in a result set
$columns[] = $col['name'];// get name from metedata
}
print_r($columns);
For mysqli
$rs = $cid->query('SELECT * FROM commissions');// your query
$col = $rs->fetch_fields();//Returns metadata for a column in a result set
foreach ($col as $val) {
$columns[]=$val->name;
}
print_r($columns);

Delete database tables with php\mysql

I am trying to list all the tables in a database into an array and then proceed to delete the tables contents. What is wrong with my code?
<?php
mysql_connect('localhost', 'root','');
mysql_select_db(database_name);
$res = mysql_query("SHOW TABLES");
$tables = array();
while($row = mysql_fetch_array($res, MYSQL_NUM)) {
$tables[] = "$row[0]";
}
$length = count($tables);
for ($i = 1; $i < $length; $i++) {
$res = "DELETE FROM $tables[$i]";
mysql_query($res);
echo $res;
$i++;
}
?>
At the end of your for loop you don't need to do $i++; anymore, as this operation is already included in the for loop.
The code you have at the moment will delete the contents of one table and then skip a table, delete contents of one table again and skip one again...
Also $i should start with 0 as the first element in an array in php is element 0.
for ($i = 0; $i < $length; $i++) {
$res = "DELETE FROM $tables[$i]";
mysql_query($res);
echo $res;
}

how do I traverse rows in a table

I have a table named members with 3 rows. The following code attempts to display all the rows in the members table. It displays the 1'st record 3 times instead of displaying each record once.
<?php
$con = new mysqli("localhost", "root", "jce123", "profile");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
$keysarray = array_keys($array);
$valuearray = array_values($array);
for ($i=0; $i < $num; $i++) {
for($j = 0; $j < count($array); $j++) {
echo "<table>";
echo "<tr><td>".$keysarray[$j].": </td><td>".$valuearray[$j]."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
mysqli_close($con);
?>
I've updated this per suggestions:
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
$array = mysqli_fetch_assoc($res);
while ($row = mysqli_fetch_assoc($res)) {
foreach($array as $key => $value){
echo "<table>";
echo "<tr><td>".$key.": </td><td>".$value."</td></tr>";
echo "</table>";
}
echo "<br><br>";
}
That's because, your $num = 3, count($array) = 3 and the outer for loop has no bearing on inner for loop.
Where you have $array = mysqli_fetch_assoc($res);, you will only receive one row from your database. You need something like:
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
}
Any basic tutorial will tell you this. Even the PHP docs provide an example.
you can use do something like this..
while ($row=mysqli_fetch_assoc($res))
{
// processing for each row
e.g
echo $row['id'];
echo $row['name'];
etc
}
try this... this peace of code is not tested but just to give you an idea...
$sql = "SELECT * FROM members";
$res = mysqli_query($con,$sql);
$num = mysqli_num_rows($res);
while ($row = mysqli_fetch_assoc($res)) {
echo "<table>";
echo '<tr><td> id = "'.$row['id'].'":
</td><td> name = "'.$row['name'].'"</td></tr>";
echo "</table>";
}

Categories