Sql and Php, insert into sql select option - php

i have one form in php, in this form have one select option
<select id="birdname" style="width: 150px; height: 25px; border-radius: 5px;">
<option>--Cambiar vendedor --</option>
<?php
$selectagent = "SELECT * FROM `" . $prefix . "user`";
$resultforagents = mysql_query($selectagent);
while ($agent = mysql_fetch_object($resultforagents)) {
?>
<option value="<?= $agent->user_id ?>" ><?= $agent->username ?></option>
<?php } ?>
</select>
<div id="stage" style="display:none;"></div>
Showing name of username, i need insert selected username (reference not name) into sql
<?php
$userId = $_POST['birdname'];
$idtill = $_SESSION['caj'];
$cashid = $_SESSION['cash'];
$mvalue = number_format($givenamount, 2, '.', '');
$mdate = date("Y-m-d H:i:s");
$moption = '1';
$sql = "INSERT INTO `" . DB_PREFIX . "order_user`(`user_id`, `order_Id`, `till`, `value`, `operation`, `comment`, `date`,`cashid`) VALUES ('" . $userId . "','" . $lastorderidis . "','" . $cashid . "','" . $mvalue . "','" . $moption . "', '" . " " . "', '" . $mdate . "','" . $cashid . "')";
$common->showresultsql($sql, 'update', 1);
echo $lastorderidis;
?>
Thanks

Add the name tag to your select value to get the value of select like this:
<select id="birdname" name="birdname">
Now you will have the value by $_POST['birdname']
More info here: get the selected index value of <select> tag in php

Related

am trying to move specific table data to another while deleting from previous table (php & sql)

The code does not perform the task/operation i want and it does not return any error. Note that i have added another column on tblchristianout to record the reason for the removal of selected member That is the problem am facing another issue will be adding the searching option on the select box for selecting a member, i have tried using seclect2 and chosen to add the feature but i have not succeded if i can get assistance on that matter also it will be much appreciated
<?php
session_start();
error_reporting(0);
include('includes/dbconnection.php');
if(isset($_POST['save']))
{
// Get the selected ID
$ID = $_POST["ID"];
$reason = $_POST['reason'];
// Select specific data from the old table
$sql = "SELECT * FROM tblchristian WHERE ID = $ID";
$result = mysqli_query($conn, $sql);
// Move the data to the new table
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$sql = "INSERT INTO tblchristianout (name, Code, number, Age, Sex, Occupation, Status, Country, Parish, Village, District, Email, Phone, Photo, Marital, Registeredby, lastname, Birthdate, CreationDate, reason)
VALUES ('" . $row["name"] . "','" . $row["Code"] . "','" . $row["number"] . "','" . $row["Age"] . "','" . $row["Sex"] . "','" . $row["Occupation"] . "','" . $row["Status"] . "','" . $row["Country"] . "','" . $row["Parish"] . "','" . $row["Village"] . "','" . $row["District"] . "','" . $row["Email"] . "','" . $row["Phone"] . "','" . $row["Marital"] . "','" . $row["Registeredby"] . "', '" . $row["lastname"] . "', '" . $row["Birthdate"] . "', '" . $row["CreationDate"] . "', '" . $row["reason"] . "')";
mysqli_query($conn, $sql);
}
}
// Delete the moved data from the old table
$ID = $_POST['ID'];
$sql = "DELETE FROM tblchristian WHERE ID = $ID";
if (mysqli_query($conn, $sql)) {
echo "Data moved and deleted successfully";
} else {
echo "Error deleting data: " . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<div class="card-body">
<!-- Date -->
<form role="form" id="" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="card-body">
<div class="form-group">
<label>Tarehe:</label>
<div class="input-group date" id="reservationdate" >
<input type="date" name="date" class="form-control " required />
</div>
</div>
<div class="form-group ">
<label for="exampleInputPassword1">Jina la Mshiriki</label>
<select name="name" class="anyname form-control" data-live-search="true" required>
<option value="">chagua Mshiriki</option>
<?php
$sql="SELECT * from tblchristian";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach($results as $row)
{
?>
<option value="<?php echo $row->ID;?>"><?php echo $row->name;?></option>
<?php
}
} ?>
</select>
</div>
<div class="form-group ">
<label for="exampleInputPassword1">Ondolewa Kwa</label>
<select name="reason" class="form-control">
<option value="Uhamisho">Uhamisho</option>
<option value="Kifo">Kifo</option>
<option value="Kuasi">Kuasi</option>
</select>
</div>
</div>
<div class="modal-footer text-right">
<button type="submit" name="save" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
my include/dbconnection.php code
<?php
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','churchdb');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
}
catch (PDOException $e)
{
exit("Error: " . $e->getMessage());
}
$conn = mysqli_connect("localhost","root","","churchdb");
?>

PHP update table in MySQL not working

My php won't update my products table. I know my GET request worked as I tested it with echo to display the id. I am confused as to how I can get it to work? I think it may be something to do with the form action= on my form but I am confused! Can someone please help?
<?php
// Connection file
require 'db.php';
if (((!empty($_GET["mode"])) && (!empty($_GET["id"]))) && ($_GET["mode"] == "update")) {
// If update
echo $_GET['id'];
if (isset($_POST["updateSubmit"])) {
$pName = $_POST["updateProductName"];
echo $pName;
$query = "UPDATE products "
. "SET p_name = '" . $_POST["updateProductName"] . "', "
. "p_type = '" . $_POST["updateProductType"] . "', "
. "p_desc = '" . $_POST["updateProductDesc"] . "', "
. "p_price = '" . $_POST["updateProductPrice"] . "', "
. "p_stock = " . $_POST["updateProductStock"] . ", "
. "WHERE id=" . $_GET['id'] . ";";
$result = mysqli_query($conn, $query);
}
}
?>
<div>
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&id=" . $productDetails["id"]; ?>" method="post">
<label>Product name:</label><br>
<input type="text" name="updateProductName"><br>
<label>Product type</label><br>
<select name="updateProductType">
<option value="Jackets/coats">Jackets/coats</option>
<option value="Accessories">Accessories</option>
<option value="Shirts">Shirts</option>
<option value="Jeans">Jeans</option>
<option value="Trousers">Trousers</option>
<option value="Shoes">Shoes</option>
<option value="Suits">Suits</option>
</select>
<p>Product description:</p>
<textarea name="updateProductDesc" rows="10" cols="30"></textarea><br>
<label>Product price:</label><br>
<input type="text" name="updateProductPrice"><br>
<label>Stock level:</label><br>
<input type="text" name="updateProductStock"><br>
<input type="submit" name="updateSubmit" value="Submit">
</form>
</div>
<?php
?>
I think the problems are misusing of ' in one or both of these lines
. "p_price = '" . $_POST["updateProductPrice"] . "', "
. "p_stock = " . $_POST["updateProductStock"] . ", "
If the type is string you need to use ' as you used in p_price otherwise if it is float or int you should not use ' as you did for p_stock.
It seems you used wrong for these two field. Since the p_price would be float and p_stock is string.
. "p_price = " . $_POST["updateProductPrice"] . ", "
. "p_stock = '" . $_POST["updateProductStock"] . "' , "
There are two issues with your query...
You Have one extra comma before the Where Section and your missing delimeters on p_stock.
Should be:
"p_stock = '" . $_POST["updateProductStock"] . "' "
and
. "WHERE id='" . $_GET['id'] . "'";

Unknown column 'xxxxxx' in 'field list'

I know there are a lot of topics on this, and I've looked at them all, and they don't help me. My table name is correct, no spaces or anything out of the ordinary. I've checked 100 times and checked 100 more. I'll post both bits of my code, and hopefully someone can help.
I get this error when I try to use the submit button:
Error updating odds: Unknown column 'homeOdds' in 'field list'
POST:
if ($_POST['action'] == 'Update') {
foreach($_POST['game'] as $game) {
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$sql = "update " . $db_prefix . "schedule ";
$sql .= "set homeOdds = '" . $homeOdds . "', visitorOdds = '" . $visitorOdds . "' ";
$sql .= "where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());
}
header('Location: index.php');
}
Table/Form & Update button:
<form id="scoresForm" name="scoresForm" action="odds.php" method="post">
<input type="hidden" name="week" value="<?php echo $week; ?>" />
<?php
$sql = "select s.*, ht.city, ht.team, ht.displayName, vt.city, vt.team, vt.displayName ";
$sql .= "from " . $db_prefix . "schedule s ";
$sql .= "inner join " . $db_prefix . "teams ht on s.homeID = ht.teamID ";
$sql .= "inner join " . $db_prefix . "teams vt on s.visitorID = vt.teamID ";
$sql .= "where weekNum = " . $week . " ";
$sql .= "order by gameTimeEastern";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
echo '<table cellpadding="4" cellspacing="0" class="table1">' . "\n";
echo ' <tr><th colspan="6" align="left">Week ' . $week . '</th></tr>' . "\n";
$i = 0;
while ($result = mysql_fetch_array($query)) {
$homeTeam = new team($result['homeID']);
$visitorTeam = new team($result['visitorID']);
$rowclass = (($i % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '>' . "\n";
echo ' <td><input type="hidden" name="game[' . $result['gameID'] . '][gameID]" value="' . $result['gameID'] . '" />' . date('D n/j g:i a', strtotime($result['gameTimeEastern'])) . ' ET</td>' . "\n";
echo ' <td align="right"><input type="hidden" name="gameID[' . strtolower($visitorTeam->team) . ']" value="' . $result['gameID'] . '" />' . $visitorTeam->teamName . '</td>' . "\n";
echo ' <td><input type="text" name="game[' . $result['gameID'] . '][visitorScore]" id="game[' . $result['gameID'] . '][visitorScore]" value="' . $result['visitorOdds'] . '" size="3" /></td>' . "\n";
echo ' <td align="right"><input type="hidden" name="gameID[' . strtolower($homeTeam->team) . ']" value="' . $result['gameID'] . '" />at ' . $homeTeam->teamName . '</td>' . "\n";
echo ' <td><input type="text" name="game[' . $result['gameID'] . '][homeScore]" id="game[' . $result['gameID'] . '][homeScore]" value="' . $result['homeOdds'] . '" size="3" /></td>' . "\n";
echo ' </tr>' . "\n";
$i++;
}
echo '</table>' . "\n";
}
?>
<br><input type="submit" name="action" value="Update" />
</form>
Any help is appreciated.
For debugging this, echo (or var_dump) the dynamically generated SQL contained in the $sql variable, before you submit it to the database.
Then take that statement to another client to test it.
MySQL is telling you that the table schedule which you are referencing doesn't contain a column named homeOdds.
We don't see the contents of all the variables that are being incorporated into the SQL text. (The code appears to be vulnerable to SQL Injection.

insert multiple post with one request in table opencart

Trying to insert a query multiple records in the database, but get an error:
Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in
Below I attach the code type and model
Please show where the error or where and in what direction the engine
view
<tr class="green_table">
<td class="td">
<input type="text" name="forma[]" />
<?php if ($error_forma) { ?>
<span class="error"><?php echo $error_forma; ?></span>
<?php } ?>
</td>
<td class="td">
<input type="text" name="linkto[]" />
</td>
<td class="td">
<input type="text" name="description[]" />
<?php if ($error_description) { ?>
<span class="error"><?php echo $error_description; ?></span>
<?php } ?>
</td>
<td class="td">
<input type="text" name="cvet[]" />
<?php if ($error_cvet) { ?>
<span class="error"><?php echo $error_cvet; ?></span>
<?php } ?>
</td>
<td class="td">
<input type="text" name="sizes[]" />
<?php if ($error_sizes) { ?>
<span class="error"><?php echo $error_sizes; ?></span>
<?php } ?>
</td>
<td class="td">
<input type="text" name="counts[]" />
<?php if ($error_counts) { ?>
<span class="error"><?php echo $error_counts; ?></span>
<?php } ?>
</td>
<td class="td">
<input type="text" name="tcena[]" />
<?php if ($error_tcena) { ?>
<span class="error"><?php echo $error_tcena; ?></span>
<?php } ?>
</td>
</tr>
model:
foreach($data as $key => $value){
$query = $this->db->query("INSERT INTO `" . DB_PREFIX
. "order` SET customer_id = '" . (int)$data['customer_id']
."',forma = '" . $this->db->escape($data['forma'])
. "', linkto = '" . $this->db->escape($data['linkto'])
. "', description = '" . $this->db->escape($data['description'])
. "', cvet = '" . $this->db->escape($data['cvet'])
. "', sizes = '" . $this->db->escape($data['sizes'])
. "', counts = '" . (int)$data['counts']
. "', tcena = '" . (int)$data['tcena']
. "', sposob = '" . $this->db->escape($data['sposob'])
. "', delivery_usa = '" . $this->db->escape($data['delivery_usa'])
. "', hint = '" . $this->db->escape($data['hint'])
. "', novapochta = '" . $this->db->escape($data['novapochta'])
. "', customer_group_id = '" . (int)$data['customer_group_id']
. "', firstname = '" . $this->db->escape($data['firstname'])
. "', lastname = '" . $this->db->escape($data['lastname'])
. "', email = '" . $this->db->escape($data['email'])
. "', telephone = '" . $this->db->escape($data['telephone'])
. "', date_added = '" . $this->db->escape(date('Y-m-d H:i:s'))
."', order_status_id =' 1"
."'");
$new_order_id = $this->db->getLastId();
}
Thanks!
This has nothing to do with OpenCart itself, it is about basic PHP. You need to loop through all the posted values and insert one set of values at a time.
It should be like this:
$values_count = count($data['forma']);
for ($i = 0; $i < $values_count; $i++) {
$query = $this->db->query("INSERT INTO `" . DB_PREFIX . "order` SET"
. " customer_id = " . (int)$data['customer_id']
. ",forma = '" . $this->db->escape($data['forma'][$i])
. "', linkto = '" . $this->db->escape($data['linkto'][$i])
. "', description = '" . $this->db->escape($data['description'][$i])
. "', cvet = '" . $this->db->escape($data['cvet'][$i])
. "', sizes = '" . $this->db->escape($data['sizes'][$i])
. "', counts = " . (int)$data['counts'][$i]
. ", tcena = " . (int)$data['tcena'][$i]
. ", sposob = '" . $this->db->escape($data['sposob'][$i])
. "', delivery_usa = '" . $this->db->escape($data['delivery_usa'][$i])
. "', hint = '" . $this->db->escape($data['hint'][$i])
. "', novapochta = '" . $this->db->escape($data['novapochta'][$i])
. "', customer_group_id = " . (int)$data['customer_group_id'] [$i]
. ", firstname = '" . $this->db->escape($data['firstname'][$i])
. "', lastname = '" . $this->db->escape($data['lastname'][$i])
. "', email = '" . $this->db->escape($data['email'][$i])
. "', telephone = '" . $this->db->escape($data['telephone'][$i])
. "', date_added = NOW()"
. ", order_status_id = 1");
$new_order_id = $this->db->getLastId();
}
Integer values does not need to be escaped with '1' when You typecast them to (int).
You form fields are arrays like : forma[], linkto[] which cannot be used with $this->db->escape().
Please echo the variable $value within the loop foreach($data as $key => $value){ and update your code.
Have a nice day !!

Cat_id FROM categories not INSERTING into c_id in subcategories

I was discussing this issue in another question but it was getting away from the original question so I thought it would be best to make a new one.
Below is my code, everything is inserting correctly into the subcategories table accept for c_id, which is being INSERTED as 0 into my database with each entry, here is the code.
<?php
//create_cat.php
include '../includes/connect.php';
include '../header.php';
echo '<h2>Create a Sub category</h2>';
if($_SESSION['signed_in'] == false | $_SESSION['user_level'] != 1 )
{
//the user is not an admin
echo 'Sorry, you do not have sufficient rights to access this page.';
}
else
{
//the user has admin rights
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
echo '<form method="post" action="">
Category name: ';
$sql = "SELECT cat_id, cat_name, cat_description FROM categories";
$result = mysql_query($sql);
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo 'Sub category name: <input type="text" name="sub_cat_name" /><br />
Sub category description:<br /> <textarea name="sub_desc" /></textarea><br /><br />
<input type="submit" value="Add Sub Category" />
</form>';
}
else
{
//the form has been posted, so save it
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
$result = mysql_query($sql) or die (mysql_error());
echo 'The sub category <b>' . $row['sub_cat_name'] . '</b> has been added under the main category <b>' . $row['cat_name'] . '</b>';
if(!$result)
{
//something went wrong, display the error
echo 'Error' . mysql_error();
}
}
}
; ?>
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['categories.cat_id'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
should be
$sql = "INSERT INTO subcategories(c_id, sub_cat_name, sub_desc)
VALUES('" . $_POST['topic_cat'] . "', '" . $_POST['sub_cat_name'] . "', '" . $_POST['sub_desc'] . "')";
As the post field for category id is topic_cat
And try to avoid mysql_* functions due to they are deprecated.Instead use mysqli_* statements or PDO statements

Categories