I have a MYSQL table named issues_tot including following columns:
v_code, oid, amount, mod_date
02) Then I need to update or insert records of the table according to the given condition as follows:
if(($vt == $vote)||($of == $ono)){
03) update is working properly, but insert is not (else part). My code is showing below:
if (isset($_POST["submit"]))
{
$ono =$_POST["oid"];
$amt =$_POST["amt"];
$allo=mysql_fetch_array(mysql_query("SELECT * FROM allocation WHERE al_code='{$_GET['al_code']}'"));
$vote=$allo['v_code'];
$current_date = date("Y-m-d H:i:s");
$query ="select * from issues_tot where v_code='$vote' ";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$vt = $row['v_code'] ;
$of = $row['oid'] ;
if(($vt == $vote)||($of == $ono)){
$query ="UPDATE issues_tot SET oid = $ono, amount = amount + $amt WHERE v_code=$vote";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}else {
$query ="INSERT INTO issues_tot (v_code, oid, amount, mod_date) VALUES ('$vote', '$ono', '$amt', '$current_date')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}
}
I can not understand what I am going wrong. Can anyone help me ?. Pls
Related
I'm making a form that submits a story into a MySQL table called 'work'. I want to later take the id of the newly created record and put the information into a different table.
But when I submit the story, it says:
$workid is undefined.
I can't see the problem though because I believe I've defined it?
<?php
if (!empty($_POST) && !empty($_POST['title']) && !empty($_POST['story']) && !empty($_POST['genre']) && !empty($_POST['rating'])) {
$title = strip_tags($_POST['title']);
$story = strip_tags($_POST['story']);
$title = mysqli_real_escape_string($db, $title);
$story = mysqli_real_escape_string($db, $story);
$genre = $_POST['genre'];
$rating = $_POST['rating'];
$query = "SELECT COUNT(*) AS count FROM works WHERE Title = '".$title."'";
$result = $db->query($query);
$data = $result->fetch_assoc();
if ($data['count'] > 0) {
echo "<p>Story already exists!</p>";
} else {
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$query = "SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc())
$workid = $row["id"]; //workid is written here but still considered undefined
}
$query = "INSERT INTO `author_work` (`author_id`) VALUES ('".$authorid."')";
$result = $db->query($query);
$query = "INSERT INTO `author_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`work_id`) VALUES ('".$workid."')";
$result = $db->query($query);
$query = "INSERT INTO `login_work` (`login_id`) VALUES ('".$userid."')";
$result = $db->query($query);
if ($result) {
echo "<p>Story submitted!</p>";
} else {
echo "SQL Error: " . $db->error;
}
}
}
?>
You never did a $db->query() on your INSERT INTO... query string, so it was never inserted, and was overwritten by your SELECT id ... query.
$query = "INSERT INTO works (author_id, login_id, Title, Story, Genre, Rating) VALUES ('".$userid."','".$authorid."','".$title."','".$story."','".$genre."','".$rating."')";
$db->query($query); // Missing this $db->query()
$query="SELECT `id` FROM `works` WHERE `Title` = '".$title."'";
if ($result = $db->query($query)) {
while ($row= $result->fetch_assoc())
$workid = $row["id"];}
Your $workid might not be initialized, depending on your condition and the result of your SQL query: so try to avoid next operations that will causes warnings/errors by using continue or else
Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
I have sql + php query and i need inform user when update fail exmpl:
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
sqlsrv_query( $con, $sql);
And now if php variables values not 100% match values in db update fails but users cant see that. He can check records and try again. I would like inform him when query update nothing.
Like GOB commented, you can use the PHP sqlsrv_rows_affected function to retrieve the number of affected rows. For example:
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_rows_affected( $stmt );
if ($row_count === false)
echo "Error in retrieving row count.";
else
echo $row_count;
Before directly executing update query,check whether condition in update query exists or not. This can be done by selecting count of that condition.
Try below code:
$sql = "select count(*) as count from db WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' ";
while($row = mysqli_fetch_array($sql))
{
$count = $row['count'];
}
if($count == 0)
{
echo 'update will fail';
}
else
{
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
}
This seems to always return 1 for $item_result->num_rows; even though there are 0 rows in the DB. However, if an item exists it updates the row correctly. I'm sure something is wrong with my syntax but I'm having a hard time wrapping my head around this mysqli.
$item_query = "SELECT COUNT(*) FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result = $mysqli->query($item_query) or die($mysqli->error.__LINE__);
if($item_result->num_rows==1) {
$item_query2 = "SELECT * FROM `rel` WHERE `cart_id` = '".$cartId."' && `id_item` = '".$item_id."'";
$item_result2 = $mysqli->query($item_query2) or die($mysqli->error.__LINE__);
$getOldItems = $item_result2->fetch_array();
$oldQty = $getOldItems['amount'];
$oldNotes = $getOldItems['notes'];
$newQty = $oldQty + $item_quantity;
$newNotes = $oldNotes . $item_notes;
$update_qty = $mysqli->query("UPDATE rel SET amount = '$newQty', notes = '$newNotes' WHERE `cart_id` = '$cartId' && `id_item` = '$item_id'");
if(!$update_qty){
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
} else {
$insert_cart_item = $mysqli->query("INSERT INTO rel (`email`, `cart_id`, `id_item`, `amount`, `notes`) VALUES ('$email', '$cartId', '$item_id', '$item_quantity', '$item_notes')");
if(!$insert_cart_item) {
printf("Errormessage: %s\n", $mysqli->error);
}
header('Location: ./ordernew.php');
}
When you do SELECT COUNT(*) there will always be at least one result. Even if its 0.
You will need to fetch the result of the query to get the correct count.
I am trying to use a value that I receive from a MySQL query and then do an insert but it's not working. I'm getting an syntax error but the Insert Query is correct.
The select query returns an amount which I'm checking and then the program should do the insert query.
<?php
require 'header.php';
$resID = mysql_real_escape_string($_POST['resID']);
$materialen_id = mysql_real_escape_string($_POST['materialen_id']);
$aantal = mysql_real_escape_string($_POST['aantal']);
$effectief_gebruikt = mysql_real_escape_string($_POST['effectief_gebruikt']);
$opmerking = mysql_real_escape_string($_POST['opmerking']);
//$datum_van = date('d-m-Y', $_POST['datum_van']);
//$datum_tot = date('d-m-Y', $_POST['datum_tot']);
$datum_van = $_POST['datum_van'];
$datum_tot = $_POST['datum_tot'];
$sql = "SELECT `aantal_beschikbaar`
FROM `materialen`
WHERE `id` = $materialen_id";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$tot = $row['aantal_beschikbaar'];
echo 'totaal: ' . $tot;
}
$sql2 = "SELECT `aantal` FROM `materialen_per_reservatie`
WHERE `materialen_id` = $materialen_id";
$result2 = mysql_query($sql2) or die(mysql_error());
while ($row = mysql_fetch_array($result2))
{
//$aant = $row['aantal'];
//echo $aant
echo $row['aantal'];
}
$besch = ($tot - $aant);
echo 'beschikbaar: ' . $besch;
/*$sql3 = "SELECT * FROM `materialen_per_reservatie`
WHERE `reservaties_id` = $resID
AND `materialen_id` = $materialen_id";
$result3 = mysql_query($sql3) or die(mysql_error());*/
if($besch > $aantal){
$string2 = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
mysql_query($string2) or die(mysql_error());
}
require 'footer.php';
?>
Provided that the error is on only the insert query...
Your insert query is missing a needed space:
INSERT INTO `materialen_per_reservatie` (`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')
Add a space after materialen_per_reservatie. And I'm not sure you need all of the quotes.
INSERT INTO materialen_per_reservatie (reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')