I think my mind is just drawing a blank, but basically, I want to create an associative array from various sql results
The array needs to look like:
$people = array(
"+1123456789" => "Phil"
);
Here is my SQL Statement
$sql = " SELECT phonenumber6, firstName FROM members WHERE departmentID = 4 AND phonenumber6 <> '+1';";
Thanks!
Edit:
Also, there can be multiple rows that were selected by the sql statement
$sql = " SELECT phonenumber6, firstName FROM members WHERE departmentID = 4 AND phonenumber6 <> '+1';";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result)) {
echo $people[$row['phonenumber6']] = $row['firstName'];
}
while($row=mysql_fetch_assoc($query)) {
$people[$row['phonenumber6']] = $row['firstName'];
}
Addendum
Dunno what you want to echo. Anyway the right syntax is:
while($row=mysql_fetch_assoc($query)) {
$people[$row['phonenumber6']] = $row['firstName'];
echo $row['phonenumber6']. '=> '.$row['firstName']."<br />\n";
}
This will give you an associated array from a mysql result set:
$assoc = mysql_fetch_assoc ($res);
Related
how can i add result of multiple queries in a single array so it makes it easier to later output.
for example,
$newArray = array("mike", "john");
while ($newArray !== false){
$sql = "Select * from accounts where name = '$newArray'";
$result = mysqli_query($db_connection,$sql);
}
while ($row = mysqli_fetch_assoc($result)) {
printf $row['firstName'];
echo "----";
printf $row['num_accounts'];
echo "----";
prinf $row['location'];
echo "----";
echo "<br>";
}
i am sure i am missing something that obvious. but the idea is that i want to setup a loop to read from an array and then execute the query and store the results. each time query executes the condition is different but from same table, , but then keep adding the results to single output, making it easier to output in the end.
you could avoid the while simple using in clause based on list of values you need
$newList = "'mike', 'john'";
$sql = "Select * from accounts where name IN (" .$newList .")";
but you should not use php var in sql ..you are at risk for sqlinjection .. for avoid this you should take a look at your sqldruver for binding param ..
but if you want append the result for different where condition on same table you should take a look at UNION clause
$sql = "Select * from accounts where name IN (" .$newList .")
UNION
Select * from accounts where you_col > 10";
There's a few things wrong with your code..
1. You are inputting a full array into your query.
2. You're doing no preparations on your query thus it's vulnerable to sql injection if $newArray is human input data.
3. Your logic from looping thru the data, if you managed to get a single query correct, would always loop thru the last query. You need to move the $row = mysqli_fetch_assoc($result) stuff inside your actual loop.
To get this code working it would look like so:
$newArray = array("mike", "john");
foreach($newArray as $name){
$sql = "Select * from accounts where name = '{$name}'";
$result = mysqli_query($db_connection,$sql);
while ($row = mysqli_fetch_assoc($result)) {
printf $row['firstName'];
echo "----";
printf $row['num_accounts'];
echo "----";
prinf $row['location'];
echo "----";
echo "<br>";
}
}
For my school I need to Select items from the MySQL Server and it only should show the name and the price.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
$row = mysqli_fetch_array($query);
foreach($row as $values)
{
echo "<p>".$values["item"]."</p>";
echo "<p>".$values["price"]."</p>";
}
I only got something like:
L
L
L
L
4
4
4
4
Its the only first item in the table but there are many rows in DB.
you're doing fine, but what you're doing wrong is, you're picking just one item and iterating over that single value.
Here you're extracting only LLLL4444 and looping on this only, so, in order to get all.
You need to do this.
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}
Try this:
$sql = "SELECT `item`,`price` FROM `items` ";
$query = mysqli_query(con(), $sql);
while ($row = mysqli_fetch_assoc($query)) {
echo "<p>".$row["item"]."</p>";
echo "<p>".$row["price"]."</p>";
}
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.
So using mysql_fetch_array() without specifying MYSQL_ASSOC or MYSQL_NUM, or by specifying MYSQL_BOTH will return two arrays
I am using PHP/MySql to display some results from a database.
CODE
$query = "select * from users where (fname like '%".$searchTerm."%') OR (lname like '%".$searchTerm."%')";
$result = $db->query($query);
echo "yoooo";
$num_rows = $result->num_rows;
echo "<br/>".$num_rows." results st 2";
for ($i=0; $i<$num_rows ; $i++) {
$row = $result->fetch_assoc();
$fn = $row['fname'];
$ln=$row['lname'];
echo "<br/>".stripslahes($fn)." ".stripslashes($ln);
}
This shows:
yoooo
1 results st 2
But nothing more... Why? I am sure that the names I use in the associative array are the column names in the table...
I'd try to:
turn on error_reporting(E_ALL)
echo the query + make sure $searchTerm is safe(avoid sql injections)
var_dump($row)
Hi what's the best way to do a 'order by' from a query without executing a query for another time? Lets say I have a search query when I have to find names or surnames using a form ,an example :
//Array for storing WHERE part of query
$where=array();
if(!empty($name)) AND !empty($surname)){
$where[]="Name LIKE '%$name%'" .
"AND Surname LIKE '%$surname%'";
}
elseif(!empty($name)){
$where[]="Name LIKE '%$name%'";
}
elseif(!empty($surname)){
$where[]="Surname LIKE '%$surname%'";
}
$where = implode(' AND ', $where);
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
$name = $row[0];
$surname = $row[1];
echo"$name";
echo"$surname";
}
How can I display Name or Surname in ASC mode(ORDER BY Name ASC) after my search"Name LIKE %surname%",without executing again the SQL query? I want for example when I search for a name containing "ich"word to have a list in this way:
MICHAEL
PICHAEL
XICHAEL
=> the ASC mode
XICHAEL
PICHAEL
MICHAEL
=> the DESC mode
I really don't think I'm understanding your question correctly, but I'm going to go out on a limb here and guess you just want to order by two different columns?
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC, Surname ASC";
by the way you had an extra " in your query string
Also, you may want to look into using mysql_fetch_assoc instead of mysql_fetch_array
This is just me nitpicking now ... but instead of using:
echo"$name";
echo"$surname";
You can just write:
echo $name;
echo $surname;
Arr you talking about reversing the order of an array like this?
<?php
//Array for storing WHERE part of query
$where=array();
if(!empty($name) && !empty($surname)){
$where[]="Name LIKE '%$name%'" .
"AND Surname LIKE '%$surname%'";
}
elseif(!empty($name)){
$where[]="Name LIKE '%$name%'";
}
elseif(!empty($surname)){
$where[]="Surname LIKE '%$surname%'";
}
$where = implode(' AND ', $where);
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name";
$res = mysql_query($sql);
$names = array();
$surnames = array();
$wholeNames = array();
$x='0';
while ($row = mysql_fetch_array($res)) {
if(!empty($row['Name'])){
$names[$x] = $row['Name'];
}
if(!empty($row['Surname'])){
$surnames[$x] = $row['Surname'];
}
if(!empty($row['Name'])&&!empty($row['Surname'])){
$wholeNames[$x] = $row['Name'].' '.$row['Surname'];
}
$x++;
}
print "<pre>\n";
print_r ($names);
print_r ($surnames);
print_r ($wholeNames);
print "</pre>\n";
$reversed_names=array_reverse($names);
$reversed_surnames=array_reverse($surnames);
$reversed_wholeNames=array_reverse($wholeNames);
print "<pre>\n";
print_r ($reversed_names);
print_r ($reversed_surnames);
print_r ($reversed_wholeNames);
print "</pre>\n";
?>
Something to watch out for, if you're using LIKE with the wildcards a search for "Art" would match Bart, Arthur, carter, and any other word with "Art" in it.
When I try to mysql_fetch_row the array that is created contains 2 fields from my selection at each index. I would like to ask why is this happening?
<?php
$categoryid = $_GET['id'];
include('connect.php');
$query = "SELECT
Categories_SubCategories.IdCategory,Categories_SubCategories.idSub_Category,
Categories.Name, Sub_Categories.Name from Categories_SubCategories JOIN
Categories on Categories.idCategory = Categories_SubCategories.idCategory
JOIN Sub_Categories on Categories_SubCategories.idSub_Category =
Sub_Categories.idSub_Category
WHERE Categories_SubCategories.IdCategory = $categoryid";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for($i=0; $i<$rows; $i++){
$display = mysql_fetch_row($result);
echo "$display[3]";
}
?>
most PHP programmers use while() loop when they want to work with mysql_fetch_array().
Take a look at this sample code:
$query = mysql_query("SELECT id,name FROM tbl_members");
if (mysql_num_rows($query)) {
while ($result = mysql_fetch_array($query)) {
echo('User #'.$result['id'].' is: '.$result['name'].'<br />');
}
}
// Output can be something like this:
// User #1 is: John
// User #2 is: Sarah
replace mysql_num_rows with mysql_fetch_array or mysql_fetch_assoc