How to update table from query(MYSQL) - php

I have problem write back to table with UPDATE from mysql_fetch_assoc. I got it to work with INSERT but then it add a new row.
Is there anybody who can help me with the correct syntax?
I heve this query:
$sql = "SELECT * FROM oppgave WHERE modulid=5 AND resultat is NULL ORDER BY RAND() LIMIT 1";
$data = null;
$dataid = null;
$result = mysql_query($sql, $tilkobling);
echo "<hr>";
while ($nextrow= mysql_fetch_assoc($result)){
echo "Svar: " . $nextrow['besvarelse'];
echo "<br>Modulid: " . $nextrow['modulid'];
echo "<br>student: " . $nextrow['studentid'];
echo "<br>";
$data = $nextrow['modulid'];
$dataid = $nextrow['id'];
}
echo '<form name="input" action="tilretting.php" method="post">';
echo'Retter<input type="text" name="correctedby" value="'.$_SESSION['myusername'].'">';
echo '<input type="hidden" name="resultat" value="0">';
echo 'Godkjent<input type="checkbox" name="resultat" value="1">';
echo 'modul<input type="text" name="modulid" value="'.$data.'">';
echo 'id<input type="text" name="id" value="'.$dataid.'">';
echo '<input class="levermodulknapp" type="submit" name="lever1" value="Send inn retting">';
echo "</form>";
echo "<hr>";
?>
I And this is that i tryed put in the php who is submitted:
<?php
include "header.inc.php";
//in this file the connetion to server
include "funksjoner.inc.php";
$correctedby= $_POST['correctedby'];
$resultat= $_POST['resultat'];
$data = $nextrow['modulid'];
$dataid = $nextrow['id'];
//Step 2: connetion to db
$tilkobling = kobleTil(); //trenger ikke oppgi databasenavn
//Steg 3: Kjør en SQL-query
$sql = "UPDATE oppgave SET correctedby='".$correctedby."', resultat='".$resultat.", WHERE id='".$dataid."'";
mysql_query($sql, $tilkobling);
?>
What am i doing wrong?
So grateful for any tip on this one!

You are doing unnneccessary concatenations and there is an extra comma before the WHERE clause..
The right way..
$sql = "UPDATE oppgave SET correctedby='$correctedby', resultat='$resultat' WHERE id='$dataid'";

Related

Trying to update a single item's quantity when an item is "purchased" from my store, but every item in my table is updated. Why?

Please understand- I am not experienced with PHP. But I know I am close to figuring this out.
I have a table, generated by a while loop (getting data from a MySQL database), that gives the customer a list of albums from an artist. I want the customer to be able to input the quantity of the album they wish to purchase, and have the database update appropriately. I can get the code to loop through and update every album in my table (based on user input), but that is obviously not what I want. How can I make it so only ONE album is updated at a time??
Here is my code:
<div id = "MusicSearch"><h4>Search For Music</h4></div>
<div id="search">
<form method="post" action="get-records.php?go" id="searchform">
<input type="text" name="artistName">
<input type="submit" name="submit-form" value="Search">
</div>
<?php
if(isset($_POST['submit-form'])){
$artistName = $_POST['artistName'];
if(isset($_GET['go'])){
if(preg_match("/^[A-Za-z]+/", $_POST['artistName'])){
include 'include/connect.php';
$sql = "
SELECT y.artistName
, x.albumName
, x.albumID
, x.cost
, x.stock
FROM album x
JOIN artist y
ON x.artistID = y.artistID
WHERE y.artistName LIKE '%" .$artistName. "%'
";
$result = $con->query($sql);
echo '<table><tr><th>Artist</th><th>Album</th><th>Cost</th><th>Stock</th><th>Quantity</th></tr>';
?>
<?php
while ($row = $result->fetch_array()) {
$albumName=$row['albumName'];
$cost=$row['cost'];
//$albumID=$row['albumID'];
$stock=$row['stock'];
echo '<tr>';
echo '<td>' . $artistName . '</td>';
echo '<td>' . $albumName . '</td>';
echo '<td>' . $cost . '</td>';
echo '<td>' . $stock . '</td>';
?>
<td><form method="post" action="get-records.php">
<input type="hidden" name="albumID[<?php echo $row['albumID']; ?>]" value="<? echo $row['albumID']; ?>"></input>
<input type="number" name="quantity[<?php echo $row['albumID']; ?>]" value="<?php echo $row['quantity']; ?>"></input>
<input type="submit" name="purchase-form" value="Purchase"/></form></td>
<?php
}
echo "</table>";
}
}
}
if(isset($_POST['quantity'])){
foreach($_POST['albumID'] as $key => $id){
$quan = mysqli_real_escape_string($con, $_POST['quantity'][$key]);
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = albumID";
try{
$result = $con->query($q);
if (!$result)
echo "Error, try again " . mysqli_error($con);
if(is_null('id'))
throw new Exception('Error. Try again');
}
catch (Exception $ex) {
echo '<div class="error">' . $ex->getMessage() . '</div>';
}
}
}
?>
replace your update query with this UPDATE album SET stock = 'stock-".$quan."' WHERE albumID = '".$id."'
May you need to use $_POST['albumID']'s value Instead of albumID, here
$q = "UPDATE album SET stock = stock-$quan WHERE albumID = $id";
albumID = albumID is true for all rows that's why its updating all records

using form textfield name from dynamic table outside whileloop

I got another problem with my Code.
I generate a dynamic table from SQL-content and use textfields in the table to, maybe someday, change the content.
The problems is, I cann't access the textfields from outside the whileloop to save the content, all I get is Undefined index error for every field.
<form method="POST" enctype="text/html">
<?php
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
echo "<tr>";
echo "<td>";
echo '<table border="1" width="80%" align="center">';
echo "<tr> <th>Name</th><th>Stand</th><th>Verbrauch</th><th>Einzahlungen</th></tr>";
while ($zeile = mysql_fetch_assoc($db_erg))
{
echo '<tr>';
echo '<td>'. $zeile['name'] . '</td>';
echo '<td><center>'. $zeile['bier_stand'] . '€</td>';
echo '<td>';
/* in the text below, i set the name to verbrauch"'.$zeile['id'] and
ergebnis"'.$zeile['id'] which should generate a new unique name for every
single text*/
echo '<center><input type="text" name="verbrauch"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '<td>';
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
echo '</td>';
echo '</tr>';
} echo '</table>';
?>
<center><input type="hidden" name="aktion" value="speichern" />
<center><input type="Submit" name="" value="speichern"/>
</form>
<?php
if (isset ($_POST['aktion']))
{
if ($_POST['aktion'] == "speichern" )
{
require_once ('config.php');
$sql = " SELECT * FROM kassen ORDER BY name ASC ";
$db_erg = mysql_query( $sql );
while ($zeile = mysql_fetch_assoc($db_erg))
{
$standalt = $zeile["bier_stand"];
/* now I try to put the value of the text to the DB, but all i get is
Undefined Index error */
$verbrauch = $_POST['verbrauch'.$zeile['id']];
$einzahlung = $_POST['einzahlung'.$zeile['id']];
$stand = $zeile["bier_stand"] - $verbrauch + $einzahlung;
$id = $zeile["id"];
$sql = "UPDATE kassen SET ";
$sql .= " bier_stand_alt = '$standalt', ";
$sql .= " bier_stand = '$stand', ";
$sql .= " bier_verbrauch = '$verbrauch', ";
$sql .= " bier_einzahlungen = '$einzahlung' ";
$sql .= " WHERE id='$id'";
}
echo '<h2>Änderungen übernommen</h2>';
echo 'zurück zur Bierkasse';
exit;
}
}
?>
Any idea what I'm messing up?
Sorry for questioning,
realy stupid mistake
echo '<center><input type="text" name="einzahlung"'.$zeile['id'].' value="0" size="10" />';
should have been
echo '<center><input type="text" name="einzahlung'.$zeile['id'].'" value="0" size="10" />';
so actually just the " was in wrong place ... stupid stuff that happens at 3am

Search Data not outputting the correct results

This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.
Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.

How do I reduce the number of variables and connections for php connecting to mysql server?

I am trying to reduce the number of connections that this page makes. Everything I read says that only one connection should be enough however if I remove the additional connections the page doesn't connect to my server and provide me the results I am looking for. Also one of the queries I am using twice but if I call the original query the second time it also does not work.
What am I doing wrong?
<?php
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequnce, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysql_query($sql);
mysql_connect($dbaddress, $dbuser, $dbpass);
mysql_select_db($dbname);
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysql_query($sql2);
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysql_query($sqlstart);
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysql_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysql_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>
Once a connection is open in a page you don't need to re-open it for each query. You can simply remove all the statements that create a connection and select the database, except the first one.
Note you're using mysqli to open the connection, but mysql to query it. The two sets of functions are not interchangeable: use mysqli as 'mysql' is deprecated and support will be removed in the future.
Try this:
$dbaddress="localhost";
$dbuser="testuser";
$dbpass="testpass";
$dbname="testdb";
$dbtable="elo";
$query="SELECT Sequence, mcacctname FROM `elo`;";
$con=mysqli_connect($dbaddress,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Sequence, mcacctname FROM `elo`;";
$result = mysqli_query($con,$sql) or die(mysqli_error($con));
$sql2 = "SELECT Sequence, mcacctname FROM `elo`;";
$result2 = mysqli_query($con,$sql2) or die(mysqli_error($con));
$sqlstart = "SELECT mcacctname, elo FROM `elo`;";
$q = mysqli_query($con, $sqlstart) or die(mysqli_error($con));
?>
<form name="player1" method="post" action="predictions.php">
<label for="Select Player 1">Select Player 1:
<?php
echo "<select name='elouser1'>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Sequence'] . "'>" . $row['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 1 Wins">
</form>
<br>
<form name="player2" method="post" action="predictions.php">
<label for="Select Player 2">Select Player 2:
<?php
echo "<select name='elouser2'>";
while ($row2 = mysqli_fetch_array($result2)) {
echo "<option value='" . $row2['Sequence'] . "'>" . $row2['mcacctname'] . "</option>";
}
echo "</select>";
?>
</label>
<input type="submit" value="Player 2 Wins">
</form>
<table>
<tr>
<?
echo '<div class="container">';
while($res = mysqli_fetch_array($q)){
echo '<tr><td><div class="item">'. $res['mcacctname'] . '</td><td>' . $res ['elo'] . '</div></td></tr>';
}
echo '</div>';
mysqli_close($con);
?>
</tr>
</table>

Unknown Column In Where Clause mysql query

My query is $query = "SELECT * FROM cartmatch WHERE CARTNO=$cart4"; and I'm receiving an error that says "Unknown column 'M833' in 'where clause'". Just so you know, cart4=M833.
::EDIT::
For some reason, nothing is showing. Here is the code on the page.
<?php
$cart1 = rawurldecode($_GET["path"]);
list( , , , , , $cart2) = explode ("\\", $cart1);
$cart3 = $cart2;
list($cart4) = explode (" ", $cart3);
$con = mysql_connect("SERVER","USERNAME","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cartmatch", $con);
$result = mysql_query("SELECT * FROM cartmatch WHERE CARTNO='$cart4'");
while($row = mysql_fetch_array($result))
{
echo '<form enctype="multipart/form-data" action="album.php" method="POST">Please enter press save.<br><br><input name="ID" type="hidden" value=';
echo $_GET["ID"];
echo ' ><input name="enabled" type="hidden" value=';
echo $_GET["enabled"];
echo ' ><input name="artist" type="hidden" value=';
echo $_GET["artist"];
echo ' ><input name="title" type="hidden" value="';
echo $_GET["title"];
echo '" >Name:<br/><input name="album" type="text" autofocus="autofocus" value="';
echo $row['ALBUM'];
echo '" ><input type="submit" name="edit" value="Save"></form>';
}
mysql_close($con);
?>
Change the query to:
"SELECT * FROM cartmatch WHERE CARTNO='$cart4'"
and change
list($cart4) = explode (" ", $cart3);
to
list($cart4) = explode ("+", $cart3);
Change the WHERE section to
CARTNO='$cart4'

Categories