PHP update table in MySQL not working - php

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'] . "'";

Related

Querying for checking quiz in php [duplicate]

This question already has answers here:
The 3 different equals
(5 answers)
Closed 5 years ago.
querying is my problem to choose the correct answer .
.
.
.
please answer my problem
*
<?php
$sql = "SELECT * FROM questions_exam_tbl WHERE exam_id = '" . $_POST['subject'] . "'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row['test_num'] = $qnumber){
echo '
<h3>' . $row['test_num']. '. ' . $row['test_question'] . '</h1>
<input type="radio" name="choiceA" value="' . $row['choice_A'] . '"> ' . $row['choice_A'] . '
<input type="radio" name="choiceA" value="' . $row['choice_B'] . '"> ' . $row['choice_B'] . '
<input type="radio" name="choiceA" value="' . $row['choice_C'] . '"> ' . $row['choice_C'] . '
<input type="radio" name="choiceA" value="' . $row['choice_D'] . '"> ' . $row['choice_D'] . '
';
}
}
?>
*
if($row['test_num'] = $qnumber)
should be
if($row['test_num'] == $qnumber)
Single = is for value assigning. For comparison it is == or ===.

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 !!

mysql update script

Anyone who can point a php novice in the right direction? It won't update the database and I can't figure it out. I get the article that I want to change and put it a form, and use the "update1.php" file to update the database.
Getting the article:
<?php
include ('../db_connect.php');
$getid = $_GET['artikkelID'];
$query = mysql_query('SELECT tittel, ingress, publ, tekst, forfatter, bildetekst, photo FROM hovedartikler WHERE artikkelID = "' . $getid . '"');
$rows = mysql_fetch_assoc($query);
$titteldb = $rows['tittel'];
$ingressdb = $rows['ingress'];
$tekstdb = $rows['tekst'];
$forfatterdb = $rows['forfatter'];
$bildetekstdb = $rows['bildetekst'];
$photodb = $rows['photo'];
echo '<form action="update1.php" method="post" enctype="multipart/form-data">
<span>
ArtikkelID
<input type="text" name="artikkelID" readonly="readonly" size="3" value="' . $getid . '">
</span>
<span style="margin-left: 20px;">
Artikkelens Tittel ( maks 100 tegn)
<input type="text" name="tittel" cols="80" size="50" value="' . $titteldb . '" /><br />
</span>
<br />
Ingress (maks 255 tegn)<br />
<textarea name="ingress" rows="4" cols="60" />' . $ingressdb . '</textarea><br />
Artikkelens tekst (ingen begrensning på antall tegn)<br />
<textarea id="textarea1" name="tekst" size="100%">' . $tekstdb . '</textarea>
<script language="javascript1.2">
generate_wysiwyg("textarea1");
</script>
Skriv inn artikkelens forfatter (maks 50 tegn)<br />
<input type="text" name="forfatter" size="80" cols="80" value="' . $forfatterdb . '" /><br />
Skriv inn tekst til artikkel-bilde<br />
<textarea name="bildetekst" rows="3" cols="60">' . $bildetekstdb . '</textarea><br />
Last opp bilde til bruk i artikkelen<br />
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="file" name="file" size="80" value="' . $photodb . '" /><br />
<br />
<input type="submit" name="submit" value="Oppdater" />
</form>';
?>
And the update-script:
<?php
$id = $_POST['artikkelID'];
$tittel = $_POST['tittel'];
$ingress = $_POST['ingress'];
$tekst = $_POST['tekst'];
$forfatter = $_POST['forfatter'];
$bildetekst = $_POST['bildetekst'];
$pic = $_FILES['file']['name'];
include '../db_connect.php';
if(isset($_POST['Oppdater']))
$mysql_query=("UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'")
or die (mysql_error());
mysql_query($query);
echo "Artikkelen er oppdatert!<br/><br/>
Du vil nå automatisk bli dirigert til Admin-forsiden.";
print_r($ingress);
mysql_close();
?>
<script type="text/javascript">
setTimeout("window.location.href='http://mss-seil.no/admin/adminIndex.php'", 3000);
</script>
All help appreciated!
For a start stop using mysql_* functions and start using mysqli or PDO and prepared statements with bound values or you will face SQL injection attacks.
Secondly, for now change mysql_query($query) to mysql_query($mysql_query) and remove the brackets from around the actual query and the die statement when setting the variable. You are trying to run the query held in $query but the UPDATE query is actually held in $mysql_query
It should look more like this:
$mysql_query = "UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'";
mysql_query($mysql_query);
$mysql_query=("UPDATE hovedartikler SET tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'") or die (mysql_error());
Note it's "$mysql_query" not "$query".
mysql_query($mysql_query);
Just a few side notes too:
the mysql_* functions should not really be used now. Take a look at mysqli or PDO.
You are not sanitizing your input before inserting it into the database. This is not a good idea - you're leaving yourself wide open to SQL injection attacks. You should escape strings and cast integers as integers. If you follow the first suggestion and use PDO or mysqli, look into using prepared statements.
Hope that helps!
Please look for SQL-Injections and escape your values from $_POST, please :) - And the Javascript-redirect can be replaced with a server-sided PHP-redirect with "header", I guess.
$mysql_query=("UPDATE hovedartikler SET
tittel='" . $_POST['tittel'] . "', ingress='" . $_POST['ingress'] . "', tekst='" . $_POST['tekst'] . "', forfatter='" . $_POST['forfatter'] . "', bildetekst='" . $_POST['bildetekst'] . "', file='" . $_FILES['pic'] . "' WHERE artikkelID='$id'")
or die (mysql_error());
mysql_query($query);
You've got a variable "$mysql_query" with the Update-Statement. But you send a variable "$query" to the mysql_query function. Shouldn't you send the $mysql_query variable to the mysql_query function? Maybe better variable names could be helpful :)
I do not know if this is the cause but you are using different quotes in the two files.
In the getting:
"' . $getid . '"'
And in the setting
WHERE artikkelID='$id'"
What datatype is artikkelID?
If it is an int, the first will work as double quote is not a string quote but a "grouping" quote which can be used to have columns with reserved words names
The last will not work as single quote IS a string quote, and you cannot use string for an int column.
For example
I could query an int column like this
WHERE id > "20"
but not like this
WHERE id > '20'
Whereas for a string column
WHERE name = "Hello World"
Would try to match the name column with the Hello World column, not the Hello World string

Insert into value of Radio button

I am trying to insert the value of a radio button when its checked into mysql db table. Below is the HTML and the PHP for doing so. Please let me know what is going wrong?
Here is the HTML first:
<div class='container'>
<label for='username' >Business*:</label><br/>
<input type="radio" name="bus" id="username" value="bus" maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
<div class='container'>
<label for='username' >Personal*:</label><br/>
<input type="radio" name="pers" id="username" value="per" maxlength="50" /><br/>
<span id='register_username_errorloc' class='error'></span>
</div>
Now the PHP:
function InsertIntoDB(&$formvars)
{
$confirmcode = $this->MakeConfirmationMd5($formvars['email']);
$formvars['confirmcode'] = $confirmcode;
$insert_query = 'insert into '.$this->tablename.'(
name,
email,
username,
password,
confirmcode,
dob,
business,
personal
)
values
(
"' . $this->SanitizeForSQL($formvars['name']) . '",
"' . $this->SanitizeForSQL($formvars['email']) . '",
"' . $this->SanitizeForSQL($formvars['username']) . '",
"' . md5($formvars['password']) . '",
"' . $confirmcode . '",
"' . $this->SanitizeForSQL($formvars['dob']) . '",
"' . $this->SanitizeForSQL($formvars['bus']) . '",
"' . $this->SanitizeForSQL($formvars['pers']) . '"
)';
if(!mysql_query( $insert_query ,$this->connection))
{
$this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
return false;
}
return true;
}
I think there is a logical error. You should only save one of the variable in radio button in database.
"' . $this->SanitizeForSQL($formvars['bus']) . '",
"' . $this->SanitizeForSQL($formvars['pers']) . '"

Categories