Get ID for each array element inside second array - php

I need to get unique ID for each array element inside second array. That ID already exist in table but I cant get them separately. URL that am getting now looks like this: http://page.com/index.php?p=view&m=area&id=173id=552id=768id=36id=217id=
I need just one ID and if first is used set second and so on.
I know that I should use mysqli or PDO and normalized tables but that later, now I need help with this.
This is the code:
$res= mysql_query("SELECT * FROM area WHERE user='$user' ORDER BY date") or die("Error: " . mysql_error());
while($row = mysql_fetch_assoc($res))
{
$id = $row['id'];
$x = array();
$parent = array();
foreach($row as $value)
{
if ($value == $id) continue;
else if ($value == $user) continue;
$result = explode(",", $value);
foreach($result as $newvalue)
{
$query = "SELECT x,firm FROM list where list.x='$newvalue'";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$x[] = $r['x'];
$xx = implode("id=",$x);
$parent[] = $r['firm'];
$list = implode("<a href='index.php?p=view&m=area&$xx'>", $parent)."</a>";
}
}
echo "<td><span>" . $list . "</span>/td>";
}
Thank you

first of all
$list = implode("<a h
should be
$list .= implode("<a h

That URL syntax is not the correct way to pass an array of values to a PHP script. It should use PHP array syntax for the parameter names. Also, you need separate your parameters with an ampersand (&):
http://page.com/index.php?p=view&m=area&id[]=173&id[]=552&id[]=76&8id[]=36&id[]=217
Then you can get the second one by using
$second_id = $_GET['id'][1]; // 552
etc.
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Related

Mysql to mysqli or PDO

I have a project here that has a LOT of this kind of code below.
It is everything in mysql and I want to change do mysqli or PDO.
The problem is that the code make the fields of the table be variables, inside the loop. So, If I need to change to something different, I will have to re-write thousand of lines of code. Because inside the loops below I will change every call of the var. Example: $row["product_name"] instead of $product_name
This is the code:
$query = "SELECT product_name, product_price from products";
$result = mysql_query($query_sql);
while($row = mysql_fetch_array($result)) {
$j = mysql_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysql_field_name($query,$i);
$$k = $row[$k];
}
//Here, inside the loop, I use $product_name instead of $row["product_name"]
}
It there a way to change the code to do the same with mysqli or PDO? I want to keep using $field_name instead of $row["field_name"].
mysqli object method shown. I don't recommend doing it this way, but it can be done. I would highly suggest you learn how to deal with either a result object or array directly. Dynamically setting variables like this will introduce a lot of unnecessary overhead.
$result = $mysqli->query($query_sql);
while($row = $mysqli->fetch_assoc($result)) {
extract($row);
//Here, inside the loop, I use $product_name instead of $row["product_name"]
}
Here is what you are looking for: http://www.doctrine-project.org/
I specifically do not like this specific project, because it tends to be slow with larger amounts of data, but provides what you need:
You specify domain classes (understand map database lines to php objects) and you only have to specify the exact name of the table column, if it does not match up with the class variable name.
So you set every column once for every object type and you use that definition throughout you code, you are making a request for the object, that has a mapping to the database.
so it goes like: $entitiy_manager->getReference('myobject', $objectid = 1 );
Creating a new object is just adding a new instance of the class.
If I understood you properly this should be you are looking for.
Thank you for every answer and opinion, but I just found the solution for my question.
I will leave here, for future reference.
This code is in mysql:
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$j = mysql_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysql_field_name($query,$i);
$$k = $row[$k];
}
}
And this would be the same in mysqli:
$result = mysqli_query($link, $query);
while($row = $query->fetch_assoc())
{
$j = mysqli_num_fields($query);
for($i=0;$i<$j;$i++) {
$k = mysqli_fetch_field_direct($query, $i)->name;
$$k = $row[$k];
}
}

Passing each row of a mysql query to a php array

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}

mysql query is not fetching all the elements from the table

it's just fetching the first element from the table.
Table name is categories which contains 2 columns : id, category
I cant understand why is it fetching just first row from the table.
<?php
$sql = "SELECT category FROM categories";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//print_r($row);
?>
You need to iterate through the result set in order to retrieve all the rows.
while($row = mysql_fetch_assoc($result)) {
print($row);
}
Also, stop using mysql_ functions. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
Use this in while loop :
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
Just like you wrote mysql_fetch_assoc($result); will get only one row. You have to use loop to get it all.
If you call mysql_fetch_assoc just once, you'll get only the first row...
while(false !== $row = mysql_fetch_assoc($result)) {
print_r($row)
}
The function you are using only does one record.
Try. ..while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['category'];
echo "";
}
For retrieve result set Use loop as per your need
foreach
Use when iterating through an array whose length is (or can be) unknown.
as
foreach($row as $val)
{
echo $val;
}
for
Use when iterating through an array whose length is set, or, when you need a counter.
for(i=0;i<sizeof($row);i++)
{
echo $row[$i];
}
while
Use when you're iterating through an array with the express purpose of finding, or triggering a certain flag.
while($row=mysqli_fetch_array($query))
{
echo $row['flag'];
}

PHP Array comparison and filtering

I'm newer to PHP and sorting out some code. This is taking two phone number lists… then pulling the numbers in the 2nd list OUT of the first list, making a new filtered list. The full code worked fine when just pulling in one list. Now that I've modified it to filter the list based a 2nd list, the code now fails and I'm getting this warning:
Warning: Illegal string offset 'phone_number' in /var/www/html/send.php on line 7
// Get all of the phone numbers from the List
$sql = "SELECT phone_number FROM dial_list WHERE list_id='$list'";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$all_people[] = $row['phone_number'];
}
// Get phone numbers from our DNC list
$sql = "SELECT phone_number FROM dial_dnc";
$result = mysqli_query($link, $sql);
echo mysqli_error($link);
foreach ($result as $row)
{
$dnc_people[] = $row['phone_number'];
}
// Remove DNC numbers from list
$filtered_people = array_diff($all_people, $dnc_people);
foreach ($filtered_people as $row)
{
$people[] = $row['phone_number'];
}
Line 79 (where the warning comes from) is:
$people[] = $row['phone_number'];
Any help to pinpoint the error or an improvement on how to accomplish this filtering would be greatly appreciated!
You forgot to fetch results from your resultset
foreach ($result as $row) {
should be
while ($row = mysqli_fetch_assoc($result)) {
This can be easily done with mysql alone.
SELECT
dl.phone_number
FROM dial_list AS dl
INNER JOIN dial_dnc as dnc
ON (dl.phone_number = dnc.phone_number)
WHERE list_id='$list'
your $result is a traversable object, not an array. as seen in the docs
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You can loop over the results in 2 different ways:
// precedural style
while ($row = mysqli_fetch_assoc($result)) { ... }
// OOP style
while($row = $result->fetch_assoc()) { ... }
Since you assign $all_people and $dnc_people with $row['phone_number'], $filtered_people doesn't have a phone_number key, instead being number-keyed, probably. Try
foreach($filtered_people as $key => $value)
{
$people[] = $value;
}

PHP mySQL get table headers function

I'm trying to build a PHP function that allows me to have an array of the headers of MySQL database for finding a particular field.
function table($tablename,$id) {
$post = mysql_query("SELECT * FROM $tablename WHERE ID = '$id'");
}
How would I then output the table headers as effective miniature queries for the row in question.
eg. $post->title, $post->timestamp, $post->field4
You need MySQLi or PDO_MySQL, but in your case:
while ($row = mysql_fetch_assoc($post)) {
echo $row['title'];
}
Documentation
Remember that the use of mysql_* function is discouraged.
A simple PHP Script to fetch the field names in MySQL:
<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
$meta=mysql_fetch_field($result,$i);
echo $i.".".$meta->name."<br />";
$i++;
}
?>
OUTPUT:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes
Hope this helps! Taken from php.net documentation.
How about mysql_fetch_assoc($post)?
To get all field names int a seperate array:
$post = mysql_fetch_assoc($post);
$fields = array();
foreach($post as $title => $value){
$fields[] = $title;
}
You can use this in a while loop to go through all rows and get theri field values(as well as their names):
while($p = mysql_fetch_assoc($post)){
$title = $p['title'];
$timestamp = $p['timestamp'];
//And so on...
}
Edit: And Pierpaolo is right, you should use another mysql implementation as the old one is gonna be removed in PHP 5.5/5.6 or a bit later...
You can get just the column names by executing this:
DESCRIBE `MyTable`;
It will return a result set that contains Field, Type, Key, etc.
$query = mysql_query("DESCRIBE `MyTable`");
while($result = mysql_fetch_assoc($query)) {
echo $result['Field'] . "\n";
}

Categories