Using id from array in dynamically generated form - php

I'm trying to dynamically generate a form from a database so that I can simply login and make changes, as well as track the votes. The form is generating fine but, I can't for the life of me figure out how to get the id from the array to post in with the data. The only successful attempt set the last one as all of their topic_id because I tried to define it in the while statement.
<?php $cat_set = fetch_categories();
if (!isset($business_name)) {
$business_name = ''; }
while($categories = mysqli_fetch_assoc($cat_set)) {
echo '<div class="category">'. "<h3>" . "Best of the Best"
.' ' . ucfirst($categories["cat_name"]) . ' ' . "</h3>";
$topic_set = get_topics_for_cat($categories["cat_id"]);
while($topics = mysqli_fetch_assoc($topic_set)) {
$topic_name = $topics["topic_name"];
echo '<div class="field">' . '<label for=' .
$topics['topic_id'] . '">' . ucfirst($topic_name) . ":" . '</label>';
echo '<input type="text"' . 'id="' .
$topics['topic_id'] . '"' . 'name="'
. $topics["topic_id"] . '"' . 'value="' .
$business_name . '"></div>';
}
echo "</div>";
}
?>
<input type="submit" value="Submit" id="submit" name="submitform"></form>
</div>
<pre>
<?php
$user_id = 3000;
if (isset($_POST['submitform'])) {
print_r($_POST);
foreach ($_POST as $business_name) {
$filtered_business_name = mysqli_real_escape_string($dbc,
$business_name);
$query = "INSERT INTO votes (";
$query .=" business_name, topic_id, user_id";
$query .= ") VALUES (";
$query .=" '$filtered_business_name', '$topics['topic_id']',
'$user_id'";
$query .=")";
$votes = mysqli_query($dbc,$query);
So more specifically I guess, what would be the best way to get $topics['topic_id'] into my query? I've tried to escape it and about everything I can think of.

Wrap the variable in curly brackets:
$query .=" '$filtered_business_name', '{$topics['topic_id']}', '$user_id'";

Do as follows:
$topic = $topics['topic_id'];
$query .=" '$filtered_business_name', '$topic', '$user_id'";

I must have just been using it wrong. I'd made so many edits and things that my own stuff didn't make sense, so I reversed a bunch and tried the key=>value thing ... and it worked right off. Now the query is:
if (isset($_POST['submitform'])) {
foreach($_POST as $key=>$value) {
$filtered_business_name = mysqli_real_escape_string($dbc, $value);
$query = "INSERT INTO votes (";
$query .=" business_name, topic_id, user_id";
$query .= ") VALUES (";
$query .=" '$filtered_business_name', '$key', '$user_id'";
$query .=")";
$votes = mysqli_query($dbc,$query);
confirm_query($votes);
}
}
Thank you everyone for your help, hopefully this will help someone with their crappy form building in the future.

Related

HTML & PHP | Filling a select with a query

I have a function that uses mysqli function that is as follows:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" .
$result['project_name'] . "</option>";
}
$return .= '</select>';
return $return;
}
The purpose of this function is to create the options and select that will be used for the Projects on my site, I know that there are 4 projects currently stored in the table, but they do not return in this function, what have I done wrong?
EDIT:
Link to screen output: (http://i.imgur.com/YIYiheH.png)
Link to code output: (http://i.imgur.com/RZsUIwQ.png)
Link to code usage: (http://i.imgur.com/4J9rvd7.png)
(Wouldn't let me do normal links)
I found the problem.
Remove the semi-colon here
while ($result = mysqli_fetch_assoc($rs));
^
that's why it's not throwing an error, because it's considered as valid syntax.
Your loop is being stopped/terminated by it.
What I think Jay and Styphon mean by their comment is that you don't do any error checking within your SELECT query. Are you sure your query is executing properly? I understand this is a relatively simple query and that you're positive there are four projects currently stored in your table, but it's always a good habit to check. Try this:
public function GetProjectOptions()
{
$return = "";
$sql = "SELECT `id`, `project_name` FROM `projects`;";
$rs = static::$link->query($sql);
$return .= '<select class="form-control" name="project">';
if($rs){
while ($result = mysqli_fetch_assoc($rs));
{
$return .= "<option value='" . $result['id'] . "'>" . $result['project_name'] . "</option>";
}
$return .= '</select>';
}else{
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
return $return;
}
I hope this helps!

php mysql $_post does not work

I have written this code, but it does not work and I cannot find any mistake. It filters data from mysql database. Below I pasted one code without $_post form and this works fine. But I need a filter due to the high volume of data.
`
include "db_connect.inc.php";
$sql = "SELECT versicherungsnamen, franchise, praemie FROM praemien";
$sql .= " where kanton = " . $_POST["kanton"]
. " and franchise = ". $_POST["franchise"];
$sql .= " order by praemie";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num==0) echo "Keine Datensätze gefunden";
while ($dsatz = mysqli_fetch_assoc($res))
echo $dsatz["versicherungsnamen"] . ", "
. $dsatz["praemie"] . "<br />";
mysqli_close($con);
?>
</body>
</html>`
But when i try this code without $_post option it works fine
<html>
<body>
<?php
include "db_connect.inc.php";
$res = mysqli_query($con, "SELECT versicherungsnamen, franchise, praemie FROM praemien");
while ($dsatz = mysqli_fetch_assoc($res))
{
echo $dsatz["versicherungsnamen"] . ","
.$dsatz["franchise"] . ","
.$dsatz["praemie"] . "<br />";
}
?>
</body>
</html>
before select replace post vars into separate variables then use this new vars in select query.
$kanton = $_POST['kanton'];
$franchise = $_POST['franchise'];
$sql = "SELECT versicherungsnamen, franchise, praemie FROM praemien where kanton = " . $kanton . " and franchise = ". $franchise. " order by praemie";
...

Produce php variable while looping through query and in certain order

I have a while fetch_assoc that produces and xml file for me. It works fine but now i need to add another variable to it.
Here is the working query
$sql3 = "SELECT name, class FROM tbl_user_tmp where user = '$user' order by name";
if(!$result3 = $mysqli->query($sql3)){
die('There was an error running the query [' . $mysqli->error . ']');
}
while($row2 = $result2->fetch_assoc()){
if(!isset($previousRow2) || !isset($previousRow2["category"]) || $previousRow2["category"] != $row2["category"])
{
$xml2 .= "\r\n";
$xml2 .= "<category title=\"" . $row2["category"] . "\" />\r\n";
}
$xml2 .= " <item drawable=\"";
$xml2 .= $row2["name"];
$xml2 .= "\" />";
$xml2 .= "\r\n";
$previousRow2 = $row2;
}
Now, what i need to do is take a array, and based on it,order what titles get done first.
This is how the array looks
$cat_order[]
Games,Apps,Google,Misc,System
You can order this in the query:
<?php
//Dynamic solution, build the SQL with a loop:
$cat_order = array("Games", "Apps", "Google");
$caseStr = "";
foreach($cat_order as $index => $value)
$caseStr .= sprintf("WHEN '%s' THEN %d ", $value, $index+1);
$sql3 = "
SELECT name, class
FROM tbl_user_tmp where user = '$user'
ORDER BY CASE name" . $caseStr . " END";
?>
Sorry to ask then answer but here is how i did it
$cat_name = $_POST['cat'];
foreach($cat_name as $k=>$val)
{
$cat_order[] = $val;
}
debug_to_console($cat_order);
$sql2 = "SELECT distinct category, name FROM tbl_user_tmp where user = '$user' and category is not null and category <> '' order by field (category,";
$size = count($cat_name);
foreach($cat_name as $k=>$val)
{
$sql2 .= "'$val'";
if($size > $k+1) $sql2 .=',';
}
$sql2 .= ")";
debug_to_console($sql2);

Is it possible to add multiple rows in one field in a database using MySQL?

So my problem is that I want to add multiple members in one team, but I cannot seem to figure out how or whether if it is even possible to do so. Here is my code for you to get my question.
<?php
$tname = $_POST['tname'];
$maxnum = $_POST['maxnum'];
$host = "localhost";
$sqluname = "root";
$sqlpass = "";
$db = "teams";
$tablename = "team info";
$mem1 = $_POST['mem1'];
$mem2 = $_POST['mem2'];
$mem3 = $_POST['mem3'];
$mem4 = $_POST['mem4'];
$connect = mysqli_connect("$host","$sqluname","$sqlpass","$db") ;
if(mysqli_connect_errno())
{
echo "Problem". mysqli_connect_error();
}
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members)
VALUES
('$tname','$maxnum','$mem1')";
/* Inside Members, I would like to add more than just $mem1, like $mem2, $mem3, $mem4.
*/
if(!mysqli_query($connect,$sql)){
die('Error: ' .mysqli_error($connect));
}
echo "Team is added";
mysqli_close($connect);
header("location: TeamDummyClient.html");
?>
$sql = "INSERT INTO teaminfo (TeamName,MaxNum,Members) VALUES";
$sql .= "('$tname','$maxnum','$mem1'),";
$sql .= "('$tname','$maxnum','$mem2'),";
$sql .= "('$tname','$maxnum','$mem3'),";
$sql .= "('$tname','$maxnum','$mem4')";
You should be escaping the strings before you insert their values to prevent SQL injections. Here's an example for one of the rows:
$sql .= "(
'" . mysqli_real_escape_string($tname) . "',
'" . mysqli_real_escape_string($maxnum) . "',
'" . mysqli_real_escape_string($mem1) . "'
),";

Variable losing its value

I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant

Categories