In the Exam1 table, ID, examname, and exam_id values are added fine. But when I try to use the UPDATE query to update the points to another table (Question), it does not work.
for($i = 1; $i<$arraysize; $i++){ //For every question
$questionid = $array[$i]['questionid'];
$points = $array[$i]['points'];
$ID = $ID+1;
$queue ="INSERT INTO Exam1 (ID, examname, exam_id) VALUES
('$questionid','$examname', '$exam_id')";
$result = mysqli_query($connection,$queue);
$queue1 ="INSERT INTO points (ID, points) VALUES
( '$ID' , '$points')";
$result1 = mysqli_query($connection,$queue1);
$sql = "UPDATE Question SET points='$points' where ID ='$questionid'";
$result1 = mysqli_query($connection,$sql);
}
$myquery = "UPDATE Question SET points='$points' WHERE ID ='" . $questionid . "'";
$resultset = mysqli_query($connection, $myquery);
Try this please
First of all be careful with int types and putting values for it in UPDATEs and INSERTs into a quote: There is type cast happening, and it may come to results, which you may not expect.
Second, I still have big trouble to understand your data model of your database: You are joining the Exam1.ID over with the Question.ID. Both appear to be the surrogates for the entity to me. Otherwise I would not understand what the meaning of the column Exam_ID (most likely coming from table Question in your case) should be. It therefore looks to me that the WHERE clause of your UPDATE statement is incomplete (did you also mean to restrict on EXAM_ID? Otherwise you might be setting all points to 20 for all questions irrespectively of the exam...?)
If I got you wrong, please provide a detailed overview about your database schema setup including the primary keys of at least the following tables:
Exam1
points
Question
to allow us further help you (and me adjusting the answer here). Also giving us some insight how you think the foreign key relationship is between the tables might help us to help you.
Related
I was wondering if it's possible to combine these two queries as they do not work separately (one of the two only works). They are
$addquery = "UPDATE winners SET mem_name='$addname' WHERE mem_name='$deletename'";
$addresult= mysqli_query($connect, $addquery);
$query = "UPDATE winners INNER JOIN members SET winners.mem_id = members.mem_id
WHERE winners.mem_name = members.mem_name";
$result = mysqli_query($connect, $query);
Can this be done in just one query? Thank you!!!
I am not saying you should do it, but judging from the flow of the code you provided, this is how you could do it.
UPDATE winners w
SET w.mem_name = '$addname'
, w.mem_id = IFNULL(SELECT m.mem_id
FROM members AS m
WHERE m.mem_name = '$addname'
ORDER BY m.mem_id DESC
LIMIT 1
, w.mem_id
)
WHERE w.mem_name = '$deletename'
;
Note, the ORDER BY is technically optional; your question does not state whether mem_name is guaranteed unique in members. If it is unique, the order by should not be needed; if it is not, it at least adds some consistency to the expected value retrieved.
If you have control over the database design, I would suggest removing mem_name from winners altogether. It is/would be redundant data if you were managing the relation primarily by mem_id to begin with.
I have ids separated like 2,3,12,22,23,24, because of adding and deleting items.
So I want to reorder them starting in 1 and set each item sequentially then set auto_increment to the last of them + 1.
I've read similar questions, but no one said why they want this, well I need this because if the ids reach the limit number (255) I won't be able to add more items in the table, and it's ridiculous because there will be like just 30 items in it.
This is probably either easy or I'm missing something, please help me.
As stated in the comments, here's my workaround for your situation (forgive the ugly hacky way to return array key 0.
This is also assuming you're using MySQLi and have already connected to the database
<?php
$query = mysqli_query($con, "SELECT `t1`.`id` + 1 FROM `grpgusers` AS `t1` WHERE NOT EXISTS (SELECT * FROM `grpgusers` AS `t2` WHERE `t2`.`id` = `t1`.`id` + 1) LIMIT 1");
$getID = mysqli_data_seek($query, 0);
$temp = mysql_fetch_array($query);
$id = $temp[0];
Then, on your insert query, add in the new $id.
For example:
mysqli_query($con, "INSERT INTOitems(name,etc.) VALUES ('{escaped postdata}', 'etc.')");
Should then be changed to:
mysqli_query($con, "INSERT INTOitems(id,name,etc.) VALUES (".$id.", '{escaped postdata}', 'etc.')");
I want to insert data to database. I have a table, named member that has 7 column (ID, User, Password, Address, Phone, Gender, Email). I used count to make auto number like this
$no = "SELECT COUNT(ID)FROM member";
$nors = mysql_query($no);
$nors = $nors + 1;
$query = "INSERT INTO member VALUES (".$nors.",'".$user."','".md5($pass)."','".$name."','".$addr."',".$hp.",'".$gender."','".$email."')";
Why, the result of nors is 6 not 2, although I only have 1 data?
mysql_query returns a result object, not the value. Your query also lacks a needed space between COUNT(ID) and FROM...
$no = "SELECT COUNT(ID) AS count FROM member";
$result = mysql_query($no);
$row = mysql_fetch_object($result);
$nors = $row->count;
You should consider using something more modern like PDO, though, as mysql_* functions have been deprecated and will eventually go away entirely.
edit: #andrewsi noted in the comments that you really should be using MySQL's built-in auto increment functionality for IDs, anyways. Much better than what you're currently doing.
If you're using this to generate the next ID number for a new member, you should look at making ID an auto_increment field instead - as it stands, it's possible that you'll get two members signing up at the same time, and both getting assigned the same ID
Replace this line
$nors = mysql_query($no);
By these lines :
$result_handler = mysql_query($no);
$result = mysql_fetch_array($result_handler);
$nors = $result[0];
If your id field is set to be an auto number you don't need to insert it. MySql will handle that for you. Anytime you add a new row the autonumber is incremented. If you delete a row the autonumber does not decrement.
If you currently only have 1 row but you've added and deleted rows then your insert will produce a row with an ID that is not consecutive.
I'm not sure how to accomplish this issue which has been confusing me for a few days. I have a form that updates a user record in MySQL when a checkbox is checked. Now, this is how my form does this:
if (isset($_POST['Update'])) {
$paymentr = $_POST['paymentr']; //put checkboxes array into variable
$paymentr2 = implode(', ', $paymentr); //implode array for mysql
$query = "UPDATE transactions SET paymentreceived=NULL";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentreceived='Yes' WHERE id IN ($paymentr2)";
$result = mysql_query($query);
$query = "UPDATE transactions SET paymentdate=NOW() WHERE id IN ($paymentr2)";
$result = mysql_query($query);
foreach ($paymentr as $v) { //should collect last updated records and put them into variable for emailing.
$query = "SELECT id, refid, affid FROM transactions WHERE id = '$v'";
$result = mysql_query($query) or die("Query Failed: ".mysql_errno()." - ".mysql_error()."<BR>\n$query<BR>\n");
$trans = mysql_fetch_array($result, MYSQL_ASSOC);
$transactions .= '<br>User ID:'.$trans['id'].' -- '.$trans['refid'].' -- '.$trans['affid'].'<br>';
}
}
Unfortunately, it then updates ALL the user records with the latest date which is not what I want it to do. The alternative I thought of was, via Javascript, giving the checkbox a value that would be dynamically updated when the user selected it. Then, only THOSE checkboxes would be put into the array. Is this possible? Is there a better solution? I'm not even sure I could wrap my brain around how to do that WITH Javascript. Does the answer perhaps lie in how my mysql code is written?
--
Edit: Ok, just more information. The SQL Queries I have going on - the first two are to wipe everything clean (in case a checkbox is UNCHECKED) and then next they are updating the SQL queries based on which checkboxes are checked upon post.
However, I'm thinking this is a bad way to do it. Why force the database to first wipe out ALL data for paymetreceived, paymetdate? The problem with this, also, is that *all the subsequent checkboxes, regardless of how long ago they were checked, get updated in the SQL query as it is now.*There's got to be a way to update it better. I'm just not sure HOW to do it. any ideas?
You are not filtering by id in this queries:
$query = "UPDATE transactions SET paymentreceived=NULL";
$query = "UPDATE transactions SET paymentdate='0000-00-00'";
Try adding: WHERE id IN ($paymentr2)";
The problem is in your first 2 sql UPDATE statements. You don't provide a WHERE clause, so that's going to update all your records. You could add:
WHERE id IN ($paymentr2)
to your first two UPDATE statements
Hey, I have a field called STATUS and it is either 1 to show or 0 to hide. My code is below. I am using an edit in place editor with jQuery. Everytime you update it creates a new ROW which I want, but I want only the new one to have STATUS = 1 and the others to 0. Any ideas on how I would do that?
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = stripslashes(mysql_real_escape_string(preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
I am not sure exactly what you mean - do you want to make all the entries except the new one have status = 0? If so, just issue an update before the insert:
UPDATE notes SET status = 0
However, I should also note that you have a potential SQL injection to worry about. By stripping slashes after applying "mysql real escape string", you are potentially allowing someone to put text in your SQL statement that will execute an arbitrary SQL statement.
Something like this, sorry for the post before, I mis read it the first time then went back:
<?php
include "../../inc/config.inc.php";
$temp = explode("_", $_REQUEST['element_id'] );
$field = $temp[0];
$id = $temp[1];
$textboxval = mysql_real_escape_stringstripslashes((preg_replace('/[\$]/',"",$_REQUEST["update_value"])));
// set older entries to 0 - to not show but show in history
$hide_notes = "UPDATE notes SET status = 0";
mysql_query($hide_notes);
// add new entry with status of 1 to show only latest note
$query = "INSERT INTO notes ($field,status,date,c_id) VALUES ('$textboxval','1',NOW(),'$id')";
mysql_query($query);
echo($_REQUEST['update_value']);
?>
i just ran in to a problem I didn't of the set up of my table doesn't allow me to show more than one client a time and i will be having numerous clients, my bad on planning ha
You really want to get the ID of the newly generated row and then trigger an UPDATE where you all rows where the ID is not the new row, e.g.
UPDATE notes SET status = 0 WHERE id != $newly_generated_id
If the ID column in your table is using AUTO_INCREMENT you can get its ID via "SELECT LAST_INSERT_ID()" and then use the return value in that statement in your UPDATE statement.
Pseudo code:
$insert = mysql_query("INSERT INTO ...");
$last_id = mysql_query("SELECT LAST_INSERT_ID()");
$update = mysql_quqery("UPDATE notes SET status = 0 WHERE id != $last_id");
The only caveat to this approach is where you might have a brief moment in time where 2 rows have status=1 (the time between your INSERT and the UPDATE). I would wrap all of this in a transaction to make the whole unit more atomic.