Search database for matching results, using PHP and MYSQLI - php

I am kind of new to all of this trying to figure out why things work and why things don't.
So I was aiming for a simple search form to display all of the database users with the same first name.
This code outputs all the names of the users in my table "users" and it works.
<?php
include 'connect.php'; //working connection to the DB
$sql="SELECT name FROM users ORDER BY name ASC";
$sqlresult=mysqli_query($con,$sql);
$afct=mysqli_affected_rows($con);
while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
$num[]=$user['name'];
$num++;
}
$i=1;
while($i < $afct)
{
echo $i.': '.$num[$i];
echo'<br>';
$i++;
}
?>
So now I wanted to add a variable that stores the user input, to match with the users first name.
<?php
include 'connect.php'; //working connection to the DB
$input = 'Marcus'; // later will be $input = $_GET(['name']);
$sql="SELECT name FROM users WHERE name='".$input."' ORDER BY name ASC";
//tried with "SELECT * FROM users WHERE name='".$input."'" ORDER BY name ASC";
//also
$sqlresult=mysqli_query($con,$sql);
$afct=mysqli_affected_rows($con);
while($user=mysqli_fetch_array($sqlresult,MYSQLI_ASSOC)){
$num[]=$user['name'];
$num++;
}
$i=1;
while($i < $afct)
{
echo $i.': '.$num[$i];
echo'<br>';
$i++;
}
?>
And all it dose is output a blank and sexy page. Thank You in Advance.
//Marcus

The problem is that you initialize $i to 1. Array indexes in PHP start at 0, just like almost every other programming language. Since your second query only returns 1 row, the only element will be $num[0]. So you should initialize $i to 0.
Or use foreach:
foreach ($num as $i => $name) {
echo "$i: $name<br>";
}
Your first script was also wrong, you just didn't notice that it skipped one of the users in the table.

i think that the second while didn't run because of $i=1 try with while($i <= $afct)

Related

echo key value from a row before postgres php while loop

Can't believe this is giving me a problem but here it is. An example of the query and code is:
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
/* I want to echo broker_id and angent_id only once here,
before the while loop, because the values are all the same */
while ($row = pg_fetch_array($sql_res)){
echo $order_number;
}
Assume broker and agent id numbers are each the same in every row. I don't want to echo them every time in the loop. I just want them to echo one time before the loop. Since they are the same, it does not matter which row they are echoed from.
I figured out a different way for a means to an end. It works well.
$sql = "SELECT
o.order_id, o.order_number, o.broker_id, o.agent_id
FROM orders o";
$sql_res = safe_query($sql);
$count = 0;
while ($row = pg_fetch_array($sql_res)){
if ($count == 0) {
echo $broker_id;
echo $agent_id;
}
echo $order_number;
$count += 1;
}
I realize I'm echoing the broker and agent IDs inside the while loop, but it's only an echo the first time through, and I can display them at top. And then every unique order is echoed. Visually, it accomplished what was needed for the end user.

How to index a table with order by?

Using a while loop I'm able to return my table in the order I want, but after implementing pagination the variable I've created (counter) resets itself on each page, frustratingly. Example code:
$sql = ('SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT 25');
$query = mysqli_query($db_conx,$sql);
$counter = 0;
while ($row = $query->fetch_assoc()) {
$counter++;
echo "$counter, $row['id'], $row['name']";
echo "<br />";
}
I've tried many things and can't get this to work. Obviously my logic is flawed. The loop returns the correct results, but the $counter variable breaks on each page, resetting itself indefinitely.
What I am trying to do is get $counter to increase by 25 (representing results for each page) for each of the pages created by the pagination loop. Example code:
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='page.php?page=".$i."'>&nbsp[".$i."]</a> ";
$GLOBALS["counter"]+=25;
};
Obviously this was not working, so I am stumped at what I should try next. If anyone has any ideas I would love to hear them, I have heard great things about the SO community.
You seem to display only the first 25 results at any time.
You need to initialize $counter to zero if it's the first page, to 26 if it's the second page, and so on :
$counter = 0;
if(isset($_GET['counter'])){
$counter = intval($_GET['counter']);
}
You need to modify your query to fetch a different set of results for each page :
$sql = 'SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT ' . mysqli_real_escape_string($db_conx, $counter . ',25');
$query = mysqli_query($db_conx,$sql);
Then I assume you display a link to the other paginated pages, you need to pass it the value of $counter :
Next

How do I scan an array and stop the scan when the number becomes false, and echo what number made the loop false in PHP

Basically I am creating a simple music player in PHP and I am setting the id of each song that is played in an array. I have a script which pulls a random number and plays the song with the corresponding id. I want to make it so that if the song has already played that it wont play again.
Currently I have it generate a random number, and if that number has already been played then it adds 1 to the random number.
The problem is if the number that is the result of adding 1 to the random number, it will then play that song again. I was attempting to store the songs played in an array and just increment the number until it doesn't exist in the array but I am struggling to find a solution to the problem.
My code is as follows:
<?php
session_start();
$con=mysqli_connect("blah blah blah");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!isset($_SESSION['played'])) {
$_SESSION['played'] = array();
}
$result = mysqli_query($con,"SELECT * FROM Data") ;
$num_rows = mysqli_num_rows($result);
$numsongs= .20 * $num_rows;
$numsongs=floor($numsongs);
$music = rand(1,$numsongs);
if (in_array($music, $_SESSION['played'])) {$music = $music+1;};
/* goes on to play music below */
$_SESSION['played'][] = $music;
?>
I didn't put my whole script in, the script works minus the repeating of songs. I only included a snippet of how I wrote the repeating script to give an idea of how I attempted it.
Thanks in advance!
I think you are looking for this...
$music = rand(1,$numsongs);
while(in_array($music, $_SESSION['played'])){
$music = $music+1;
echo 'in array '.$music;
}
echo 'Not in array '.$music;
AHAAA!! I figured it out! I ended up using switch() but in a different form.
if (empty($_SESSION['played1'])) {
for ($i = 1; $i <= $numsongs; ++$i) {
$_SESSION['played1'][] = $i;}}
shuffle($_SESSION['played1']);
$music1= $_SESSION['played1'][0];
$result = mysqli_query($con,"SELECT * FROM Data WHERE position = '$music1'") ;
while($row = mysqli_fetch_array($result)){
$del_val=$row[position];
if(($key = array_search($del_val, $_SESSION['played1'])) !== false) {
unset($_SESSION['played1'][$key]);}
Basically created an array between 1 and 10. Then used switch() to randomize the array. Then picked the first number in the array, used it in mysqli query, and then removed it from the array. Problem Solved!!

Printing SQL table header names via PHP

I have this. I'm trying to capture the SQL table header name from PHP. This works fine for me.
However I'm struggling to tune this to echo the whole list of table header names except one or two which I dont need to print.
Suppose the names of column number 10 and 15 do not need to be printed how do I tweak my attempt?
Here goes the the code thus far.
// DB1 Connection
$sql = "SELECT * FROM sal_vol;";
$result = mysqli_query($db1,$sql);
$i = 0;
while($i<mysqli_num_fields($result))
{
$meta=mysqli_fetch_field($result);
echo $i.".".$meta->name."<br />";
$i++;
}
while($i<mysqli_num_fields($result))
{
if ($i == 10 || $i == 15) continue;
$meta=mysqli_fetch_field($result);
echo $i.".".$meta->name."<br />";
$i++;
}

Problem looping through usernames

I am trying to loop through an array of usernames and for each username, execute a mysql_query on each.
<?php
for ($i = 0; $i < count($u); $i++)
{
$j = $i + 1;
$s = $database->checkUserPlayedRecent($u);
if (mysql_num_rows($s) > 0)
{
?>
<tr>
<?php
echo "<td>$j</td>";
?>
<?php
echo "<td>$u[$i]</td>";
?>
<?php
echo "<td>$p[$i]</td>";
?>
</tr>
<?
}
}
?>
As you can see, $u is each username.
I want each username to only appear in the echo statements if each one has num_rows > 0.
At the moment nothing is displaying.
But there should be results being returned!
Can someone help please.
The sql:
$q = "SELECT id FROM ".TBL_CONF_RESULTS." WHERE (home_user = '$u' OR away_user = '$u') AND date_submitted >= DATE_SUB(CURDATE(),INTERVAL 14 DAY)";
This line :
for ($i = 0; $i < count($u); $i++)
indicates that $u is an array -- and not a single name.
And $i is used to keep track of the current index in that array.
So, in your loop, you should be working with $u[$i] -- which will be the "current" line of the array :
$s = $database->checkUserPlayedRecent($u[$i]);
Note that you could probably rewrite your loop, using a foreach loop, like this :
foreach ($u as $currentPlayer) {
$s = $database->checkUserPlayedRecent($currentPlayer);
// ...
}
With foreach, no need to keep track of the current index -- makes code easier to write and understand, in my opinion ;-)
You should get in the habit of keeping count() outside of your conditional. You're count()ing the same array every time which is a waste of cycles.
$total = count($u);
for ($i=o; $i < $total; $i++) ...
I would definitely query these users all at once, especially since your query is abusing mysql_num_rows when you should be using the following sql:
select username, count(username) from user where username IN (your,array,of,usernames) group by username;
then your foreach loop would iterate over the results and you could reference each row without having to call yet another mysql_* method.
I'd be tempted to rewrite the query to accept the array of names and use an IN statement, so that you could execute the whole of your database activity in a single query rather than once for every entry in the array. It would almost certainly be faster.
If you show us the query that you're using in your checkUserPlayedRecent() method, we may be able to help with this.

Categories