How to explode() value and save it in a variable? - php

Right now I'm working on a new homepage for a museum, and I have to use the old database (because it has over 70k entries).
My job now is to change the values in the "dias" table (supporter row) from full names of the supporters to their IDs (supporter table).
Right know I'm using this code:
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", print_r($row[0]));
echo "<br>";
}
If I now put in $pate[0], I only get "1" as output (along with the names from the print_r).
My question is:
How can I split the names and save them seperately in a variable, because I think I need this to be able to compare the names with the one in the supporter table and to write the ids in the supporter row in the "dias" table.
If you need more infomration, feel free to ask.

explode needs a string as the second argument, but you are taking the return value of print_r, which is true in this case. Just take $row[0] and you should have an array of your data in $pate.
Try printing $pate after that.
$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", $row[0]);
print_r($pate)
echo "<br>";
}
After that continue :).

It looks like you are talking about List() function. list() will enable you explode into variables like;
$address ="Benson Bush|4545547 | living in California" ;
list($name ,$code , $description) = explode("|", $address);
echo $name."<br>";
echo $code."<br>";
echo $description."<br>";

$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$pate = explode(" ", $row[0]);
print_r($pate);
echo "<br>";
}

Don't do this after you've received the data - do it from your query by using SUBSTRING_INDEX:
SELECT SUBSTRING_INDEX(pate, ' ', 1) FROM dias

$result = mysql_query("SELECT pate FROM dias");
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
print_r($data);
echo "</br>";
}
print_r($data);
If you would like to stored value in variable then you can use extract function also.

Related

Filed name appearing on same line

Some code to fetch the field names by connecting it with db:
<?php
#mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM sample");
$storeArray = Array();
while ($row = mysql_fetch_array($result)) {
if (mysql_num_rows($result) > 0) {
$storeArray = $row['name'];
echo $storeArray;
}
}
?>
The above code works just fine but when it runs it gives me ramuraja. Here ramu and raja are seperate fields. But its giving me a joined output.
How can i get the two field value seperately like ramu and raja.
You print / echo the values directly after one another. Using echo $storeArray.'<br>'; would print a linebreak additionally, thus printing
ramu
Raja
However, you could also store all the variables in an array, for example with $storeArray[] = $row['name']; instead of $storeArray = $row['name'];. That would create a new array element, the value being $row['name'], while the key is incrementing for every element being added.
After having received all rows that match the query, you could loop through the array and Display the answers.
EDIT: Please check out mysqli or PDO; those PHP extensions are standard with newer versions and should be used instead of the old (and now deprecated) mysqli solution. Don't worry, they can do the same (and much more).
You need to do a for each statement to iterate through the array and echo the field along with a line break
First of all, you're declaring $storeArray as an array in this line: $storeArray = Array();, but later you replace it with a string $storeArray = $row['name'];
If you want to use $storeArray as an array, change this line:
$storeArray = $row['name'];
into
$storeArray[] = $row['name']; //add element to the array
Now loop all the results (remove echo $storeArray;)
After you've fetched all the results you kan echo them like:
foreach($storeArray as $name){
echo $name.'<br>';
}
Some confusion in code ....
first check ifthere are results:
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
....
}
}
than be more clear about what you wont:
an array :
$storeArray = Array();
or a string:
$storeArray = $row['name'];
I would so like this:
$storeArray = Array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$storeArray[] = $row['name'];
}
}
// array
print_r($storeArray);
// string
echo implode(',', $storeArray);

retrieve all datas from selected column and store

$result = mysql_query("SELECT * FROM Race");
$rows = mysql_num_rows($result);
for ($i = 0 ; $i < $rows ; ++$i)
{
$row = mysql_fetch_row($result);
echo $row[0];
}
above is probably an awkward method but it'll print out all datas stored in first column, which is good but now, I want to store each one of them into an array...
I tried
$array[$i]=$row[0];
and echoed it out, but it just prints"Array"...
I tried
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
...which does the same as code written before, i guess, since it too just print "Array".
Please help! Thank you!!
Do you use simple echo $array;? It's wrong. You can't output array this way.
Use this:
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row[0];
}
foreach($item in $array) {
echo $item."<br>"; // and more format
}
If you want to watch array contents without any format use (e.g. for debugging) print_r or var_dump:
print_r($array);
var_dump($array);
Advice: better to use assoc array.
$array = array();
$result = mysql_query("SELECT raceid FROM Race");
while ($row = mysql_fetch_array($result)) {
$array[]=$row['raceid'];
}
Advanced advice: better to use PDO and object results.
You SQL code will be invulnerable to SQL injections
Code will be more modern and readable.

How do you save rows to an array and print out in PHP using ODBC?

I have the following:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$thisResult['name'] = $myRow["name"] ;
$thisResult['race'] = $myRow["race"] ;
$thisResult['sex'] = $myRow["sex"];
$thisResult['dob'] = $myRow["dob"];
}
I can't figure out how to print this back out.
I want to get each row and iterate through each row in the array like a datareader. I'm not sure what to do. I do not want to do the echo in the while. I need to be able to print it out elsewhere. But I don't think I've done it right here to be able to print it later.
I also tried, this, however:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print($thisResult[$myRow["name"]] = $myRow);
}
I then tried:
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
print (odbc_result($myRow,"name"));
}
but got an error.
Thank you for any help.
EDIT: when I do this:
while($myRow = odbc_fetch_array( $result )){
print ($myRow["name"]);
}
I get undefined index name. I am mainly concerned with saving to an array but I have to be able to do it in the loop first.
Declare an array before and assign the values to it:
$rows = array();
while($myRow = odbc_fetch_array( $result )){ <--lots of rows
$rows[] = $myRow;
}
Then you can print it e.g. this way:
foreach($rows as $row) {
foreach($row as $key => $value) {
echo $key . ': '. $value;
}
}
or however you want to.
You don't have to access and assign $thisResult['name'] = $myRow["name"] in your while loop as $myRow already is an array. You just copy the values which is unnecessary.
You say you have a lot of rows. Depending of what you really want to do with data, it might be better to put all this functionality into the while loop to avoid creating an array.
How about something like:
$output = '';
while($myRow = odbc_fetch_array( $result )) {
$output = $output."Your name is {$myRow["name"]} and your race is {$myRow["race"]}\n";
}
// print output later...

mysql LIKE returning only one row when three match

When I query my database with the following in my file, search.php, it only returns the first result it comes across.
$qry = "SELECT business_id FROM business WHERE zip like '%91326%'";
$rs = mysql_query($qry);
$rec = mysql_fetch_array($rs);
echo $session->showContents($rec);
showContents is just a utility function...
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
showContents returned this:
Array
(
[0] => 3
[business_id] => 3
)
The crazy thing is, when I put the same query in sqlbuddy it gives me:
business_id
3
5
6
I am at a loss
mysql_fetch_array fetches only a single row. You want to use it several times to build an array with the entire result set:
$rec = array();
while(($row = mysql_fetch_array($rs)) !== FALSE) {
$rec[] = $row;
}
If you just want the ID's you want to select the ID:
$rec = array();
while(($row = mysql_fetch_array($rs)) !== FALSE) {
$rec[] = $row[0];
}
Try this:
$qry = "SELECT business_id FROM business WHERE zip like '%91326%'";
$rs = mysql_query($qry);
while ($rec = mysql_fetch_array($rs)) {
echo $session->showContents($rec);
}
That's because mysql_fetch_array only fetches a single row from the result set.
Typically you use it like this (from the manual):
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}

How to put MySQL cell values into variables named after column names in PHP

This code selects cell values in MySQL and manually adds them to PHP variables:
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)) {
$col1 = $rows['col1'];
$col2 = $rows['col2'];
$col3 = $rows['col3'];
.....
}
This is obviously unmanageable for multiple and large tables.
What's a better way to automatically generate the variable names and values without manually entering all the column names on all tables?
I think this is what you're looking for
$sql = "SELECT * FROM table LIMIT 0,1";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach ($rows as $key => $value) {
$$key = $value;
}
}
You could use extract() for that. But I'd keep the values in the array.
..SELECT x,y,z FROM ..
while( false!==($rows=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
extract($rows);
echo $x;
...
}
Wouldn't it be more convenient having associative arrays? That way you can call your variables with their column name as you describe plus you have the benefit of having them bundled in one unit which is much better if you need to pass more than one of them to any function or view or whatever.
so I would use mysql_fetch_assoc and that's it.
I don't recommend having a variable for each row, I used to do the same to simplify writing HTML later:
echo "<tr><td>$name</td><td>$count</td></tr>";
Instead of:
echo "<tr><td>{$row['name']}</td><td>{$row['count']}</td></tr>";
Until I found a better and more readable way do it using mysql_fetch_object
while ($row = mysql_fetch_object($result)) {
:
echo "<tr><td>{$row->name}</td><td>{$row->count}</td></tr>";
:
}
Use variable variables:
Code example:
$a = 'col1';
$$a = 'somevalue';
echo $col1;
will output 'somevalue'.
http://www.php.net/manual/en/language.variables.variable.php

Categories