i want to know if is possible to insert a var inside php
mysql table message i inserted in column header
"This is $Header From USA"
on my php page i have set
$Header = 'Adam';
so what i want to do is if i call mysql and and get the row from message table
and echo it
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
$msg = $row['header']);
}
echo $msg;
it should echo
This is Adam From USA
is this possible ?
Thank you
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
echo 'This is '.$row['header'].' From USA';
}
While the answers would be highly opinionated, a quick and dirty solution would be to use str_replace to parse out the desired replacement text.
$Header = 'Adam';
$result = mysql_query("SELECT * FROM `message`");
while ($row = mysql_fetch_array($result)) {
$msg = str_replace('$Header', $Header, $row['header']);
//use single quotes to ensure the variable data is not used instead.
}
echo $msg;
This is under the impression that the variable names are known, instead of needing to be eval'd, which is discouraged.
Related
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.
I have a SQL database that is being queried and needs to be sorted by a calculation based off of user input, then sorted by said calculation, then printed out.
Weird, I know.
So, with the help of the oracle known as Google, I came up with the following code:
$result = mysql_query($query) or die(mysql_error());
$buffer = array();
while($row = mysql_fetch_array($result)){
$vars;
$calc1 = [[equation]];
$calc2 = [[equation]];
$calc3 = [[equation]];
$calc4 = [[equation]];
$row['calc1'] = $calc1;
$row['calc2'] = $calc2;
$row['calc3'] = $calc3;
$row['calc4'] = $calc4;
$buffer[] = $row;
}
print "<table border='1px' cellpadding='4px' cellspacing='0'><tr><th>TABLE HEADERS</th></tr>";
foreach($buffer as $row){
print "<tr><td>";
print $row['rows....'];
print "</tr>";
}
unset($buffer, $row);
print "</table>";
mysql_close();
Obviously a lot more complex, but the code is proprietary at the moment. I will have hundreds of entries, and the calculation is as follows:
round((((($b1 / $b2) * ($bcMix * $pVm)) + (($c1 / $c2) * ((1 - ($bcMix * .01)) * $pVm)) * 12) * 5) + $pP, 2);
I also want to sort the result by two criteria: the calculation itself as well as a numerical database entry - both low to high. usort is causing my site to crash (for whatever reason):
usort($buffer, function($a, $b){
return $a['tcoy1'] < $b['tcoy1'];
});
Any suggestions?
Use array_multisort() or usort() with a custom comparison function.
Try fetch to buffer:
$result = mysql_query($query) or die(mysql_error());
$buffer = array();
while($row = mysql_fetch_array($result)){
$vars;
$calc1 = [[equation]];
$calc2 = [[equation]];
$calc3 = [[equation]];
$calc4 = [[equation]];
$row['calc1'] = $calc1;
$row['calc2'] = $calc2;
$row['calc3'] = $calc3;
$row['calc4'] = $calc4;
$buffer[] = $row;
}
// sort $buffer by 'calc1' DESC:
usort($buffer, function($a, $b){ return $a['calc1'] < $b['calc1']; });
print "<table border='1px' cellpadding='4px' cellspacing='0'><tr><th>TABLE HEADERS</th></tr>";
foreach($buffer as $row){
print "<tr><td>";
print $row['rows....'];
print "</td></tr>";
}
unset($buffer, $row);
print "</table>";
mysql_close();
You have inappropirate use of array_push(). Check the manual. Still, I don't think it even needed there.
P.S.: php_mysql extension is deprecated. I suggest to use php_mysqli or php_pdo instead.
If you're doing any complex calculations you're better off doing them in PHP and here's why:
There is support for most of the math types in PHP, in MySQL not as many.
In PHP you can handle a failed equation with a response, if you're doing them on a database server you have to pull the error, analyse and determine what happened.
Databases are designed for storing data and PHP is a programming language for running programs (and equations).
You can store the equations in a secure database table and then run them via PHP at will.
Anything with MySQL in the name is for the database only. You're doing a few extra things. I'm assuming that because you're pulling a query(although you don't show the query) that you're storing the equations in the database.
When you use mysqli_fetch_array() you're pulling the result from the database into an array already, so no need to call it twice. Anything pulled in a while() statement is going to live for the life of the while unless it's loaded into an existing var or array.
Storing the queries in the database is the tricky bit because you can store a $ character with single quotes and have it be a literal character you can use later for evaluation.
<?php
//If the vars are set then we're ready for processing
if(!empty($_POST['var1'])&&!empty($_POST['var2'])){
$query = 'select * from equations';
$result = mysqli_query($query) or die(mysqli_error());
//Create the array for storing the equations
$equations = array();
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$equation = $row['id'];
//store the equations into the array
$equations[$id]=$equation;
}
//Do some sort of check here... I'm expecting a number
if(is_numeric($_POST['var1'])){
$var1 = $_POST['var1'];
} else {
//set a default (not 0)
$var1 = 1;
}
//Do some sort of check here... I'm expecting another number
if(is_numeric($_POST['var2'])){
$var2 = $_POST['var2'];
} else {
//set a default (not 0)
$var2 = 1;
}
//Cool little function for doing equations with 2 vars being passed.
function doEquation($eq,$var1,$var2){
//eg. $eq = '$var1+$var2';
eval("\$answer=\"$eq\";");
return $answer;
}
$code = "<!doctype html>\n<html>\n<body>\n";
$code .= "<table style='padding:4px;border:none;'><tr><th>Table Header</th></tr>";
foreach($equations as $id=>$eq){
$answer = doEquation($eq,$var1,$var2);
$code .= "<tr><td>Answer $id = $answer</td></tr>\n";
}
$code .= "</table>";
$code .= "</body></html>";
} else {
//No vars set we can show them the form for the calculations.
$code = "<!doctype html>\n<html>\n<body>\n";
$code .= "<form method='post'>";
$code .= "Enter Var1<br>";
$code .= "<input type='number' name='var1' value='1' />";
$code .= "Enter Var2<br>";
$code .= "<input type='number' name='var2' value='1' />";
$code .= "<input type='submit' name='submit' value='Calculate' />";
$code .= "</form>";
$code .= "</body></html>";
}
print $code;
?>
You'll want to be careful with some of the calculations. You have to type and check all of the incoming variables. For instance you can't divide by 0 because it will throw an error. Also it is possible to load a very complicated equation with enough info to crash a server. Remember anything coming into the server that will be parsed needs to be filtered and checked against what you're expecting. You don't want to use echo commands and have someone start throwing $_SERVER vars to the screen.
Also because in my example we're using eval() you want to make sure this can't perform any additional equations or functions submitted by the user. So strip_tags() and so forth as necessary. Since my example was expecting a number, I'm checking to see if it is_numeric.
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 a mysql table in which I keep e-mail addresses. The structure is as follows:
id || email
However, how do I actually output those e-mail addresses, separated by commas, in php?
Thanks in advance for your help!
Use:
<?php
$query = "SELECT GROUP_CONCAT(t.email) AS emails
FROM YOUR_TABLE t"
// Perform Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['emails'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
References:
mysql_query
GROUP_CONCAT
Third hit on Google for "php mysql": http://www.freewebmasterhelp.com/tutorials/phpmysql
You probably need to read up on the basics, it's not complicated and will only take a few minutes to glance over it and get you started.
Option 1:
$sql = "SELECT GROUP_CONCAT(email ORDER BY email ASC SEPARATOR ', ') AS emails FROM emails";
$res = mysql_query($sql);
list($emails) = mysql_fetch_row($res);
echo $emails;
Option 2, so you can do more with all the emails later on:
$emails = array();
$sql = "SELECT email FROM emails ORDER BY email ASC";
$res = mysql_query($sql);
while ($r = mysql_fetch_object($res)) {
$emails[] = $r->email;
}
// as a list
echo implode(', ',$emails);
// or do something else
foreach ($emails as $email) {
// ...
}
Do something like:
while ($output = mysql_fetch_array($query_results)) {
echo $output['id'] . ", " . output['email'];
}
Is there any possible way to get a data from a DB using MYSQL and store it in javascript Array?
Fetch it as an associative array, and then use json_encode to create a JavaScript array, stored in a string.
.
// first, build your query:
$sql = "SELECT name, email FROM users";
$result = mysql_query($sql);
// then build up your data
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
//then write it in a way Javascript can understand:
echo "<script type=\"text/javascript\">\n"
. "var users = " . json_encode($rows) . ";\n"
. "</script>";
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
// of course this array can be created by looping through your mysql result set
// and doing a mysql_fetch_assoc
// for example, $sql = your query here
// mysql_fetch_assoc($result); etc
echo json_encode($arr);
?>
{"a":1,"b":2,"c":3,"d":4,"e":5}
Then you can do something like
<script type="text/javsacript">
var abc = "<? echo json_encode($arr);?>";
</script>
OR
echo '<script type="text/javsacript">
var abc ="'.json_encode($arr).'";
</script>';
Actually this is a pretty vague question, but I think AJAX is what you're looking
for.
EDIT: Of course JSON will workout too and might even be more straight forward...