Echo text only if MySQL value matches - php
I have two rows in my MySQL data that I would like to have code echoed only if the MySQL row data is equal to '1' (as opposed to '0'). Here's the code so far, which seems to have some severe errors:
$query = "SELECT 162, 164 FROM search WHERE title = $title";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row()) {
if ($row["162"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
if ($row["164"] = 1) {
echo '<div id="162link">1.6.2</div>';
}
}
}
$result->close();
}
$mysqli->close();
As it says in the code above the two rows are "162" and "164" in the database.
Use:
if ($row["162"] == 1)
Instead of:
if ($row["162"] = 1)
and:
if ($row["164"] == 1)
I tried for you something like this if it gives you some idea:
$host = "localhost";
$user = "myusername";
$pass = "mypassword";
$database = "WorldEngine";
$mysqli = new mysqli($host, $user, $pass, $database);
$title = "My Good News";
$query = "SELECT `162`, `164` FROM search WHERE title = '$title';";
if ($result = $mysqli->query($query)) {
$i = 0;
while ($row = $result->fetch_row()) {
if ($row["162"] == 1) {
echo '<div id="162link' . $i . '">1.6.2</div>';
}
if ($row["164"] == 1) {
echo '<div id="164link' . $i . '">1.6.4</div>';
}
$i++;
}
$result->free();
}
$mysqli->close();
The index $i is appended to the div ID in order to produce unique DOM element ID's in the HTML document. I would also suggest you to change your numerical column names into alphabet-starting names like c162, c164, ...
Hope this will help you.
Related
Using multi_query doesn't give the desired output
I am trying to query two tables from a database, while using fetch_assoc() (instead of fetch_row()). The code is below and I am not getting any data from this query. I managed to query the first table, then added some code to query the second one and now I am not getting any output. Any help will be appreciated. $mysqli = mysqli_connect($servername, $username, $password, "6dwxnmkq", 3314); if(!$mysqli){ die('Connection failed!'); } $sql = "SELECT IndexJedlo, Jedlo, Cena, Priloha FROM `jedalny_listok`"; $sql .= "SELECT index, polievka, cena FROM `polievky`"; $jedla = array(8); $ceny = array(8); $index = array(8); $polievky = array(2); $polievkyCeny = array(2); $polievkyIndex = array(2); $i = 0; if ($mysqli->multi_query($sql)) { do { if ($result = $mysqli->store_result()) { while ($row = $result->fetch_assoc()) { if($i == 0){ array_push($jedla, $row['Jedlo']); array_push($ceny, $row['Cena']); array_push($index, $row['IndexJedlo']); }else{ array_push($polievky, $row['polievka']); array_push($polievkyCeny, $row['cena']); array_push($polievkyIndex, $row['index']); } } $result->free(); } if ($mysqli->more_results()) { $i = $i + 1; } } while ($mysqli->next_result()); } $mysqli->close();
review system with function in variable
so basically I am trying to create a little thing where it outputs stars, based on the database saved rating integer. The problem is it does not seem to put the number I from the database, in the variable. Here is the code I used: <?php $productID = 100; $con = mysqli_connect("localhost", "root", "", "example"); function connect() { $con = mysqli_connect("localhost", "root", "", "example"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } else { return $con; } } function getStars($con) { $productID = 100; $sql = "SELECT rating FROM reviews -- JOIN stockitemstockgroups USING (StockItemID) -- JOIN stockgroups USING (StockGroupID) WHERE reviewID = '5' "; $result = $con->query($sql); if ($con && ($result->num_rows > 0)) { // output data of each row while ($row = $result->fetch_assoc()) { echo $row["rating"]; } } else { echo "error"; } } $value = getStars($con); echo $value; for ($x = 1; $x <= $value; $x++) { echo '<div class="rating"><span>★</span></div>'; } ?>
I'm having trouble finding a duplicate, though I'm sure this is one. You aren't returning anything from your function, so $value doesn't have a value. function getStars($con) { $productID = 100; $sql = "SELECT rating FROM reviews WHERE reviewID = 5"; $result = $con->query($sql); if ($result && ($result->num_rows > 0)) { // output data of first row $row = $result->fetch_assoc(); return $row["rating"]; } else { return false; } } As a general rule, never echo from a function. Also, no need for a loop over what will presumably be a single result.
Putting MySQL data into an array
I've tried for a couple of days to get all of the data from a MySQL column and put it inside an array, formatted in the following way: $aSpam= array ( '.info'=> 'i' , 'anal'=> 'i' , 'anus'=> 'i' , 'arse'=> 'i' ) I've managed to echo it out formatted properly as you can see here: http://www.yourgrumble.com/phpbbforum/getSpam.php with the following PHP code: <?php $servername = "localhost"; $username = "username"; $password = "pass"; $dbname = "db"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT `SpamWord` FROM spamWords"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row $counter = 0; while($row = $result->fetch_assoc()) { if($counter){ echo ", '" . $row["SpamWord"]. "'=> 'i'"; $counter++; } else { echo "'" . $row["SpamWord"]. "'=> 'i'"; $counter++; } } } else { echo "Error!"; } $conn->close(); ?> I've read and tried more than 10 solutions found in the web and here at stackoverflow, however none of them worked. I've really got desperate and I cannot get through this without your help guys. Edit For example I tried with this solution, but it didn't work: while ($row = mysql_fetch_array($result)) { $new_array[$row['id']]['SpamWord'] = $row['SpamWord']; } foreach($new_array as $array) { echo $array['SpamWord'].'<br />'; } Thank you all in advance, Denis Saidov
Try like below:- $sql = "SELECT `SpamWord` FROM spamWords"; $result = mysqli_query($conn ,$sql) or die(mysqli_error($conn)); $resultArray = array(); // create an array if ($result->num_rows > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { $resultArray[$row["SpamWord"]] = 'i'; // assing value } } else { echo "Error!"; } echo "<pre/>";print_r($resultArray); // print array $conn->close(); Note: Here you will get your original array containing all SpamWord values comes from database.thanks
PHP array's are like dictionnaries (a list of key/value pairs) First, before your loop, create your array empty: $new_array = Array(); while... Then for each column, you append the column value as a new key for the array $new_array[$row['SpamWord']] = "i"; As in your example, I put "i" as the value for each array's row.
double output from mysql in php
I am selecting the tables names from an opencart install. trying to output the result(single column) as a string formated like a JSON array. here is the code: <?php function getTableNames() { //Change these variables depending on the server it will be used on $server = 'localhost'; $user = 'User1'; $pass = 'pass'; $DBName = 'OpenCartTest'; //returns a single column of all tables in a mysql database named "OpenCartTest" $tablesGetSQL = 'Select `table_name` from `information_schema`.`TABLES` where `table_schema` like "OpenCartTest" AND `table_name LIKE "oc_customer%"'; $conn = new mysqli($server, $user, $pass, $DBName); $JSONStringArray = '['; if(mysqli_connect_errno()) { echo '---unauthorized---'; } else { $result = $conn->query($tablesGetSQL); $l = $result->num_rows; if($l > 0) { //for($i = 0;$i < $l;$i++) while($row = $result->fetch_assoc()) { //$row = $result->fetch_assoc(); foreach($row as $item) { //echo $item . "|"; $JSONStringArray .= "'" . $item . "',"; } } } $JSONStringArray .= substr($JSONStringArray, 0, -1) . ']'; $conn->close(); return $JSONStringArray; } } $output = getTableNames(); echo substr_count($output, "[") . '<br>'; echo $output; ?> The output is doubled for some reason, there are 2 '[', yet I only set it once to the string. There is also no closing ']' on the first line. output: 2 ['oc_address','oc_affiliate','oc_affiliate_activity','oc_affiliate_login','oc_affiliate_transaction','oc_api','oc_attribute','oc_attribute_description','oc_attribute_group','oc_attribute_group_description','oc_banner','oc_banner_image','oc_banner_image_description','oc_category','oc_category_description','oc_category_filter','oc_category_path','oc_category_to_layout','oc_category_to_store','oc_country','oc_coupon','oc_coupon_category','oc_coupon_history','oc_coupon_product','oc_currency','oc_custom_field','oc_custom_field_customer_group','oc_custom_field_description','oc_custom_field_value','oc_custom_field_value_description','oc_customer','oc_customer_activity','oc_customer_ban_ip','oc_customer_group','oc_customer_group_description','oc_customer_history','oc_customer_ip','oc_customer_login','oc_customer_online','oc_customer_reward','oc_customer_transaction','oc_download','oc_download_description','oc_event','oc_extension','oc_filter','oc_filter_description','oc_filter_group','oc_filter_group_description','oc_geo_zone','oc_information','oc_information_description','oc_information_to_layout','oc_information_to_store','oc_language','oc_layout','oc_layout_module','oc_layout_route','oc_length_class','oc_length_class_description','oc_location','oc_manufacturer','oc_manufacturer_to_store','oc_marketing','oc_modification','oc_module','oc_option','oc_option_description','oc_option_value','oc_option_value_description','oc_order','oc_order_custom_field','oc_order_fraud','oc_order_history','oc_order_option','oc_order_product','oc_order_recurring','oc_order_recurring_transaction','oc_order_status','oc_order_total','oc_order_voucher','oc_osapi_last_modified','oc_product','oc_product_attribute','oc_product_description','oc_product_discount','oc_product_filter','oc_product_image','oc_product_option','oc_product_option_value','oc_product_recurring','oc_product_related','oc_product_reward','oc_product_special','oc_product_to_category','oc_product_to_download','oc_product_to_layout','oc_product_to_store','oc_recurring','oc_recurring_description','oc_return','oc_return_action','oc_return_history','oc_return_reason','oc_return_status','oc_review','oc_setting','oc_stock_status','oc_store','oc_tax_class','oc_tax_rate','oc_tax_rate_to_customer_group','oc_tax_rule','oc_tg_tglite_revolution_slider','oc_upload','oc_url_alias','oc_user','oc_user_group','oc_voucher','oc_voucher_history','oc_voucher_theme','oc_voucher_theme_description','oc_weight_class','oc_weight_class_description','oc_zone','oc_zone_to_geo_zone', ['oc_address','oc_affiliate','oc_affiliate_activity','oc_affiliate_login','oc_affiliate_transaction','oc_api','oc_attribute','oc_attribute_description','oc_attribute_group','oc_attribute_group_description','oc_banner','oc_banner_image','oc_banner_image_description','oc_category','oc_category_description','oc_category_filter','oc_category_path','oc_category_to_layout','oc_category_to_store','oc_country','oc_coupon','oc_coupon_category','oc_coupon_history','oc_coupon_product','oc_currency','oc_custom_field','oc_custom_field_customer_group','oc_custom_field_description','oc_custom_field_value','oc_custom_field_value_description','oc_customer','oc_customer_activity','oc_customer_ban_ip','oc_customer_group','oc_customer_group_description','oc_customer_history','oc_customer_ip','oc_customer_login','oc_customer_online','oc_customer_reward','oc_customer_transaction','oc_download','oc_download_description','oc_event','oc_extension','oc_filter','oc_filter_description','oc_filter_group','oc_filter_group_description','oc_geo_zone','oc_information','oc_information_description','oc_information_to_layout','oc_information_to_store','oc_language','oc_layout','oc_layout_module','oc_layout_route','oc_length_class','oc_length_class_description','oc_location','oc_manufacturer','oc_manufacturer_to_store','oc_marketing','oc_modification','oc_module','oc_option','oc_option_description','oc_option_value','oc_option_value_description','oc_order','oc_order_custom_field','oc_order_fraud','oc_order_history','oc_order_option','oc_order_product','oc_order_recurring','oc_order_recurring_transaction','oc_order_status','oc_order_total','oc_order_voucher','oc_osapi_last_modified','oc_product','oc_product_attribute','oc_product_description','oc_product_discount','oc_product_filter','oc_product_image','oc_product_option','oc_product_option_value','oc_product_recurring','oc_product_related','oc_product_reward','oc_product_special','oc_product_to_category','oc_product_to_download','oc_product_to_layout','oc_product_to_store','oc_recurring','oc_recurring_description','oc_return','oc_return_action','oc_return_history','oc_return_reason','oc_return_status','oc_review','oc_setting','oc_stock_status','oc_store','oc_tax_class','oc_tax_rate','oc_tax_rate_to_customer_group','oc_tax_rule','oc_tg_tglite_revolution_slider','oc_upload','oc_url_alias','oc_user','oc_user_group','oc_voucher','oc_voucher_history','oc_voucher_theme','oc_voucher_theme_description','oc_weight_class','oc_weight_class_description','oc_zone','oc_zone_to_geo_zone'] I cannot spot where I've gone wrong. Maybe I Will try it on a diferent server next.
Don't create your JSON string manually, just use json_encode, thats why this function exists anyway: First is gather all the table names inside a container first, finish the gathering, the loop and the whole bit, after your done with that, then encode it. $result = $conn->query($tablesGetSQL); $JSONStringArray = array(); // initialize container while($row = $result->fetch_assoc()) { $JSONStringArray[] = $row['table_name']; // push all table names } // finally, encode $JSONStringArray = json_encode($JSONStringArray); $conn->close(); return $JSONStringArray;
You are getting two copies because of this line $JSONStringArray .= substr($JSONStringArray, 0, -1) . ']'; You do the .= which is doing the substr, and adding it to the original, you should just do an = ie, should just be: $JSONStringArray = substr($JSONStringArray, 0, -1) . ']'; As a side note, there's no need to build a JSON string, PHP has a built in method to generate the json string. Instead you can do $data = array(); while($row = $result->fetch_row()) { $data += $row; // append returned array to the data array, since you wanted it future proof incase you added more columns to the SELECT query } // close connection return json_encode($data);
Get Column All Values in One Array Using php [duplicate]
This question already has answers here: How to get one column of mysql_query results into an array? (4 answers) Closed 1 year ago. I have a table my_entity_data in that i have a column parentproduct_id I want to get all values of that column in side one array <?php $result = mysql_query("SELECT parentproduct_id FROM my_entity_data"); $storeArray = Array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $storeArray[] = $row['parentproduct_id']; } for ($i=0; $i < 10; $i++) { echo $storeArray[i]; } ?> But no use Any thing wrong i did here ? And i am running this code in Magento CE 1.7 Any ideas ? I
Thanks to every one finally i got it <?php // 1. Enter Database details $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'password'; $dbname = 'DB Name'; $connection = mysql_connect($dbhost,$dbuser,$dbpass); // Check connection if (!$connection) { die("Database connection failed: " . mysql_error()); } $db_select = mysql_select_db($dbname,$connection); $result = mysql_query("SELECT parentproduct_id FROM my_entity_data"); $storeArray = array(); while ($row = mysql_fetch_array($result)) { array_push($storeArray,$row['parentproduct_id']); } for ($i=0; $i < 10; $i++) { echo $storeArray[i]; } //echo sizeof($storeArray); print_r($storeArray); //to see array data ?>
you can use Try mysql_fetch_assoc($result); Below note from: php.net while ($row = mysql_fetch_assoc($result)) { foreach ($row as $key => $value) { $storeArray[$i][$key] = $value; } $i++; } for ($i=0; $i < 10; $i++) { echo $storeArray[i]; } hope this will sure work for you.
Try this <?php $result = mysql_query("SELECT parentproduct_id FROM my_entity_data"); $storeArray = array(); while ($row = mysql_fetch_array($result)) { array_push($storeArray,$row['parentproduct_id']); } print_r($storeArray); //to see array data ?>