this is really hard for me, i'm trying to store multiple rows from my table in mysql into a single variable
$mysql_statementJc = "SELECT * FROM `dog`.`cat` WHERE `name` = '$name'";
$mysql_commandJc = mysql_query($mysql_statementJc);
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$groupConcat = $followI . " OR ";
echo $groupConcat;
}
This is my appproach, so at the end of it all i can get "sam, john, bob" saved as $groupConcat which can then be used elsewhere.
Many thanks.
you want to create a concatenated string, php has the .= syntax for this:
$groupConcat='';
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat .= $row['industry'] . " OR ";
}
echo $groupConcat; //no point echoing inside the loop
sometimes a better approach is to use an array and implode()
$groupConcat=array();
while($row = mysql_fetch_array($mysql_commandJc)){
$groupConcat[] = $row['industry'];
}
echo implode(' OR ',$groupConcat);
Each time through the loop, add the desired value to an array. Then, after the loop, use the implode() function to create your desired output.
while($row = mysql_fetch_array($mysql_commandJc)){
$followI = $row['industry'];
$resultArray[] = $followI;
}
$groupConcat = implode(" OR ", $resultArray);
echo $groupConcat;
Note that you should really stop using the mysql library and instead use mysqli or PDO.
You can also do it as:
$followl = array();
while($row = mysql_fetch_array($mysql_commandJc))
{
$followl[] = $row['industry'];
}
$groupConcat = implode(" OR ",$followl);
echo $groupConcat;
Some Explanation:
Store values into an array $followl and than use implode() function for imploding with OR.
Side note:
Please use mysqli_* or PDO becuase mysql_* is deprecated and no more available in PHP 7.
Related
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.
I'm a big noob here, so I'm trying to figure it out as a I go.
I want to take a SQL request for "id, fist and last" and store each of those in a variable.
the next half of the code would be doing things with those variable.
The lower statements are simply to see if the var is begin assigned... Apparently it is not, but I get no error, just the blank lines. How can I get the info in a set to do something with?
$newIDs = mysql_query("SELECT per_ID, per_FirstName, per_LastName FROM person_per WHERE DATE_SUB(NOW(),INTERVAL 6 MONTH)<per_FriendDate ORDER BY per_FriendDate DESC") or die(mysql_error());
while($row = mysql_fetch_assoc($newIDs)){
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
//below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
print $per_ID;
echo $per_LastName;
I'm thinking you wanted something more like this for your test:
while ($row = mysql_fetch_assoc($newIDs)) {
$per_ID = $row['per_ID'];
$per_FirstName = $row['per_FirstName'];
$per_LastName = $row['per_LastName'];
// below is for testing purposes only
echo $per_FirstName;
echo "<br/>";
}
When you actually want to keep all the results from your query, you'll need to do something like:
$rows = array();
$i = 0;
while ($row = mysql_fetch_assoc($newIDs)) {
$rows[$i] = $row;
// below is for testing purposes only
echo $rows[$i]['per_LastName'];
echo "<br/>";
$i++;
}
Also, you should note that mysql_fetch_assoc() is actually a deprecated PHP function, according to the manual page: http://php.net/manual/en/function.mysql-fetch-assoc.php
echo $row ['per_ID'] = $per_ID;
should be
$per_ID=$row['per_ID'];
you echo of $per_ID; should then work
As its in a loop you will overwrite $per_ID each time and end up wit the last value.
It looks like your problem is in these statements:
echo $row ['per_ID'] = $per_ID;
echo $row ['per_FirstName'] = $per_FirstName;
echo $row ['per_LastName'] = $per_LastName;
The equals sign there assigns the value of variable $per_ID (which at that time is unassigned) to the array. That's not what you want.
Instead you probably want something like this:
$per_ID = $row ['per_ID'];
Things get further complicated by the fact that you have a while loop in which you would keep writing to the same three variables. So after the loop ends you would only have the value of the last set of fields.
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";
}
I have to create a javascript array whose elements are fetched by php from a database. Is it possible? If so, how?
(I dont want to use ajax to do that)
Collect the values in an array and convert it to JSON with json_encode:
$array = array();
while ($row = mysql_fetch_assoc($result)) {
$array[] = $row['key'];
}
echo 'var array = '.json_encode($array).';';
Answer 1: yes, it can be done.
Answer 2: Here's how:
$js_array = "[";
$result = mysql_query("some query of yours");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$js_array .= $row[0]; // assuming you just want the first field
// of each row in the array
$js_array .= ",";
}
$js_array{ strlen($js_array)-1 } = ']';
echo "var db_array = $js_array ;";
Cheers!
If you can loop through the database contents, creating an array is simple:
echo "var myArray = [";
Loop through array here and add commas to separate values.
echo "];";
Your myArray variable will be available client-side. It should look something like:
var myArray = [1, 3, 2, 4];
Alternatively and to avoid an extra comma due to loop-based string concatenation, you can write the variable to the client as follows:
echo "var myArray = [];"
...and do the following for each data row:
echo "myArray.push($db_data);"
This is effective, though not quite as clean as the previous approach. You will end up with code similar to the following:
var myArray = [];
myArray.push(3);
myArray.push(5);
myArray.push(1);
alert(myArray); // will display "3, 5, 1"
My apologies for not being too familiar with PHP, but this is something that can be done with any server-side language.
<script language="javascript1.2">
var arr = new array(<?php
$result = mysql_query("select .... ");
$count = mysql_num_rows($result);
if($count>0){
for( $i=0;$i<$count-1;$i++) {
$row = mysql_fetch_row($result);
echo $row[0],',';
}
$row = mysql_fetch_row($result);
echo $row[0],',';
}
?>);
</script>
Here is a solution that correctly deals with single quotes in the data:
First retrieve the database data, for example with mysqli_ functions:
$result = mysqli_query($con, $sql);
if (!$result) die(); // error handling comes here
$array = mysqli_fetch_all($result, MYSQLI_ASSOC);
Then convert it to JSON, escape single quotes and output the JavaScript:
$output = str_replace("'", "\'", json_encode($array));
echo "var array = '$output';";
Note that json_encode escapes backslashes (as it should) by doubling them. And it is normal that it does not escape single quotes, as it cannot know the context we put it in. So when we inject it in JavaScript, wrapping it in single quotes, we are also responsible for escaping the quotes.
You can add following lines to your php file (i assume that you have db connection file required at the top of the page)
<script>
var your_array = [<?php
$prepare_db_info=$your_db_connection->prepare("SELECT * FROM your_table_name");
$prepare_db_info->execute();
while($fetch_db_info=$prepare_db_info->fetch(PDO::FETCH_ASSOC)){
echo '"'; echo $fetch_db_info['your_column_name']; echo '"'; echo ", ";
}
?>];
</script>
Cheers,
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