Set PHP variable to MySQL data in foreach loop using array - php

I seem to have looked everywhere for this.
Here is the code i use to set a variable to a piece of data from a MySQL database
$PartNo=mysql_result($result,$i,"PartNo");
Where
$result = mysql_query("SELECT * FROM PriceList");
$i = 0, is added to by 1 every time my while loop restarts
PartNo is a field name in my MySQL table and also the name of the variable I want to set the data in the database to
PriceList is my database name
I want to loop through all the field names (the array has them) and set variables with the same names to that data. Like this:
$PartNo=mysql_result($result,$i,"PartNo");
$Group=mysql_result($result,$i,"Group");
$OnHand=mysql_result($result,$i,"OnHand");
$QOO=mysql_result($result,$i,"QOO");
$Description=mysql_result($result,$i,"Desc");
$Cost=mysql_result($result,$i,"Cost");
But with a foreach loop so it isn't as much code.
I was thinking something like this, but it won't execute no matter which way I go about it (parse_str, eval, exec, etc.)
$nDatabaseVars=array("PartNo","Group","OnHand","QOO","Desc","Cost");
foreach ($nDatabaseVars as $X) {
$$X=mysql_result($result,$i,'$X');
}
I need "$$X" to evaluate out so on the first iteration, it changes to $PartNo= and then sets $PartNo to whatever data is in the database on the first line. Which is what this part is: mysql_result($result,$i,"PartNo")
If I echo it out instead:
foreach ($nDatabaseVars as $X) {
echo "$$X=mysql_result($result,$i,'$X')";
}
I can get it to say exactly what I need executed ($PartNo=mysql_result($result,$i,"PartNo");) but not actually get the variable set.

You are passing a string containing "$X" to mysql_result, not the name of your column. Remove the single quotes:
$$X=mysql_result($result, $i, $X);

$$X=mysql_result($result,$i,'$X'); // these single quotes around $X avoid your actual string to be used.
$$X=mysql_result($result,$i,"$X");

Related

How do I put 1 variable in an array()?

I need to put a variable within an array.
For example.
$anarray = array("1","3","4");
foreach($anarray as $value){ // do such and such
I need the array() to include a variable instead. To be exact, I need it to contain a variable from my table in my database.
In effect, I would want my array to look like this.
Column 'example' in my users table contains - "1","3","4"
When I rewrite the code to look like this ...
$anarray = array($users['example']);
foreach($anarray as $value){ // do such and such
It doesn't work. What do I need to do to that variable to make it read the exact same as if it were the actual characters?
$anarray=array("1","2","3");
$new_array['example']=array();
for($i=0;$i<count($anarray);$i++){
array_push($new_array['example'],$anarray[$i]);
}

Search for all elements in a PHP array

With the updated code below, my search is working, but only using the last word in the Array. Is there a way to search the MySQL column using all words the user inputted?
Note: All input sanitization and escaping is completed in my code but not shown here.
I have two PHP arrays: $search_exploded (user inputted search terms) and $metaphoneArr (metaphones of keywords in MySQL).
I'm cycling through $search_exploded and $metaphoneArr, and if the Levenshtein is less than 2, then I'm adding the metaphone element to a third array called $levenResultsArr.
In MySQL, I'm joining two tables, and if there's a result in my third array ($levenResultsArr) that matches a row in my metaphone_col, then I want the results printed. Somehow, though, I am not referencing the third array correctly in the MySQL statement.
Any advice? Here is part of my PHP code.
$levenResultsArr = array();
foreach ($search_exploded as $search_each => $searchWord) {
$search_each2 = metaphone($searchWord);
echo $search_each2 . "<br/>";
foreach ($metaphoneArr as $metaword => $val) {
$lev = levenshtein($search_each2, $val);
if ($lev < 2) {
array_push($levenResultsArr, $search_each2);
}
}
}
// And shown below is the MySQL statement
$constructs = "
SELECT vt.idvideolist,
vt.videotitle,
vt.videodescription
FROM videolist_tbl vt
INNER JOIN keyword__video k2v ON (vt.idvideolist = k2v.video_id)
INNER JOIN keywords_tbl k ON (k2v.keyword_id = k.idkeywords_tbl)
WHERE k.metaphone_col = '$search_each2'
";
It's only searching using the last word in the array instead of all words in the array.
You're correct that you aren't referencing your array correctly in your query. You are simply referencing the variable '$search_each2'. You want to check the entire array. The best way to do this would to be to convert the array to a string using implode and using the MySQL IN clause. We need to modify the array first to format it correctly:
foreach($levenResultsArr as &$foo){
$foo = "'".$foo."'"; //add single quotes around each object in the array
}
$levenAsStr = implode(",", $levenResultsArr);
Then simply change your last line to the following:
WHERE k.metaphone_col IN (".$levenAsStr.")";
Did this from memory because I'm not in a testing environment, please let me know if there are any syntax errors. Should work for you!
Without seeing more of the code its a bit difficult to determine what is going on. A couple of thoughts though.
What var is the array containing all search terms?
I noticed you are pushing items into $levenResultsArr. I don't see it being used in the query though.
If it is $search_each_2 you may try using the IN syntax:
WHERE k.metaphone_col IN '$search_each2';
This will only match exact values however. i.e.:
some value does not return if the IN array contains value. The array would have to contain some value
If you need it to match partial searches you may try using LIKE with wildcards: %
WHERE k.metaphone_col LIKE "%searchTerm1%"
OR k.metaphone_col LIKE "%searchTerm2%"
OR k.metaphone_col LIKE "%searchTerm3%"
You could potentially use the implode function to create the sql string from the array: http://php.net/manual/en/function.implode.php

Editing the object returned by $wpdb->get_results(SQL)

We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;

Inserting textarea elements into MySQL from PHP

I need to get all the elements from a textarea in a HTML form and insert them into the MySQL database using PHP. I managed to get them into an array and also find the number of elements in the array as well. However when I try to execute it in a while loop it continues displaying the word "execution" (inside the loop) over a 1000 times in the page.
I cannot figure out what would be the issue, because the while loop is the only applicable one for this instance
$sent = $_REQUEST['EmpEmergencyNumbers'];
$data_array = explode("\n", $sent);
print_r($data_array);
$array_length = count($data_array);
echo $array_length;
while(count($data_array)){
echo "execution "; // This would be replaced by the SQL insert statement
}
you should use
foreach($data_array as $array)
{
//sql
}
When you access the submitted data in your php, it will be available in either $_GET or $_POST arrays, depending upon the method(GET/POST) in which you have submitted it. Avoid using the $_REQUEST array. Instead use, $_GET / $_POST (depending upon the method used).
To loop through each element in an array, you could use a foreach loop.
Example:
//...
foreach($data_array as $d)
{
// now $d will contain the array element
echo $d; // use $d to insert it into the db or do something
}
Use foreach for the array or decrement the count, your while loop
is a infinite loop if count is >0

mySQL loop, put the values into an array

I have the following function.
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
It requires that the variable $selected_screenshots is an array of values.
The problem is that I have to take the values from a mySQL look, that is reported below.
If there is only one value, everything works fine. But when there are more values in the DB, I cannot put all those values into the variable array.
In fact, since return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']); is outside the mySQL loop, it gets only the first value of the loop.
So how do I store all the values from the mySQL loop into the variable? And not only the first value?
I tried to manually assign the array to the variable in the loop $selected_screenshots = array($qryrow1['media_id']); but it does not work and I do not think it has any sense :)
$qry1="SELECT * FROM modzzz_articles_screenshots WHERE media_id='".$selected_screenshots_ID."' AND entry_id='".$this->aDataEntry['id']."'";
$qryr1=mysql_query($qry1) or die("Error selecting: ".mysql_error());
while($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots = array($qryrow1['media_id']);
} // END OF THE LOOK
return $this->_blockPhoto ( $selected_screenshots, $this->aDataEntry['author_id']);
Can anyone give me the solution, with code? I am really confused.
Thanks
Your code keeps overwriting $selected_screenshots with a new array each time. Instead, you want to append it:
$selected_screenshots = array();
while ($qryrow1 = mysql_fetch_array($qryr1)) {
$selected_screenshots[] = $qryrow1['media_id'];
}
You can save all the mysql values by looping through your results and appending them to the end of $selected_screenshots to do this please look below. Right now you are just assigning $selected_screenshots one value and neglecting the other values, so $selected_screenshots is having the last value that mysql returns.
This is covered http://php.net/manual/en/language.types.array.php under the heading 'Creating/modifying with square bracket syntax'

Categories