TABLE:
09:00 -- id_timeslot = 1
09.15 -- id_timeslot = 2
09.30 -- id_timeslot = 3
09.45 -- id_timeslot = 4
10.00 -- id_timeslot = 5
PHP MYSQL:
for($i=0; $i<=2; $i++) {
$mysqli->query("INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('" . ++$id_timeslot . "', '" . $id_member . "', '" . $b_ref . "', '" . $id_doctor . "', 1)" )
}
I want the data to be saved twice and increment the id_timeslot.
The above code working fine, but when save cliked. it didnt pick up the right id_timeslot?
for example: if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
if user click on id_timeslot:1, soon it save to database the id_timeslot starts from 2 instead of id_timeslot 1?
This is because you're using a pre-increment rather than a post-increment. If $id_timeslot is 1 before entering the loop, the value of ++$id_timeslot is 2, so the first generated query is:
"INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES ('2', '$id_member', '$b_ref', '$id_doctor', 1)"
If the id_timeslot column is supposed to be an ID for the bookslot record, the best approach is to declare it with the AUTO_INCREMENT attribute and don't insert values for that column:
-- run just once in some MySQL client
ALTER TABLE bookslot MODIFY id_timeslot INT UNSIGNED PRIMARY KEY AUTO_INCREMENT;
// in PHP
$stmt = "INSERT INTO bookslot(id_member, b_ref, id_doctor, status)
VALUES ('$id_member', '$b_ref', '$id_doctor', 1)";
When using double quoted strings, you don't need to concatenate variables. Compare the above statement with your own.
If id_timeslot isn't a unique ID, then you can simply switch to post-increment.
$stmt = "INSERT INTO bookslot(id_timeslot, id_member, b_ref, id_doctor, status)
VALUES (" . $id_timeslot++ . ", '$id_member', '$b_ref', '$id_doctor', 1)";
This may or may not be a correct approach for various other reasons. Without knowing more about the schema, it's impossible to say.
Off Topic
Depending on where the values for $id_member, $b_ref $id_doctor originate, your script could be open to SQL injection. Rather than inserting values directly into the string, use a prepared statement. MySQLi supports them, as does PDO, which is simpler to use. New code should use PDO, and old code should get updated over time.
You have to fetch last id_timeslot from database and then increase it PHP during inserting.
Related
I was trying with this code but it didn't work. it's always get the MAX(eq_no) as 0
$sql1 =mysqli_query($con, "SELECT MAX(eq_no) AS val FROM tech_add_equip");
$sql2 = "INSERT INTO time (eq_no,status_no) VALUES ('$val', 4 );";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con)); };
Finally, after I try with this code, it inserts in the right number of MAX(eq_no) but i still cant insert the values of status_no
INSERT INTO time (eq_no) SELECT MAX(eq_no) AS vale FROM tech_add_equip
Could you suggest me what did i missing in the code?
Thank you for your helping
One row returned from SELECT a,b,c statement in sub query is equivalent to set of values that is otherwise hardcoded as ('a-value','b-value','c-value')*. You can hardcode a value within select as well:
INSERT INTO time (eq_no, status_no)
SELECT MAX(eq_no), 4
FROM tech_add_equip
No need for aliases within select - order of columns matters.
*) One row result can be used for IN() clause. Another row would become set of values after comma - can't be uset for IN(), but it works ok for INSERT
('row1-a-value', 'row1-b-value'), ('row2-a-value', 'row2-b-value')
$max = SELECT MAX( customer_id ) FROM customers;
INSERT INTO customers( customer_id, statusno )
VALUES ($max , 4)
Hi there i am trying to insert an array of information into fields in a database through the selection of checkboxes i have that sorted and inserting fine but i am able to insert duplicates which is no good i am using the following to insert the items
$list = $_POST['sub'];
// for each loop to insert each value into the database with the selected users informtion
foreach ($list as $value) {
// The query to run
$listQuery='INSERT INTO tbl_list (`userId`, `subId`) VALUES (\'' . $id . '\', \'' . $value . '\')';
// Run the query
$objects->query($listQuery);
}
You should add a unique key for (userId, subId):
ALTER TABLE tbl_list ADD UNIQUE(`userId`, `subId`)
Then, you should use either INSERT IGNORE or REPLACE INTO to avoid errors during insert.
You can use Insert Ignore instead of Insert in mysql query
For stop duplicate entries into database you have do this thing.follow step by step
> 1.set a unique key on the table
after Complete create unique key you have to decide what you want to do when there's a duplicate
> 2. ignore it
> 3.Overwrite the previously entered record
> Update some counter
You need to do two things
first make your userId primary key and then try this query
$listQuery='INSERT INTO tbl_list (userId, subId) VALUES (\'' . $id . '\', \'' . $value . '\') on duplicate key update userId = LAST_INSERT_ID()';
How could i do a query with php and mysqli, to remove an entire table and then add new I have a form where data is received, but before adding the new data, I want to remove all data from table.
$oConni is my connection string
$cSQLt = "TRUNCATE TABLE approved";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$oConni->query($cSQLt);
$oConni->query($cSQLi);
You can remove everything from a table with MySQL by issuing a TRUNCATE statement:
TRUNCATE TABLE approved;
.. which usually is the same as
DELETE FROM approved;
.. but there are a few small differences, which you can read about in the documentation.
In the code you've pasted, please use prepared statements to avoid a sql injection attack. Never use unfiltered POST-data directly in a query!
If you want to do this as a trigger, we'll need to know a bit more about your data handling. Issuing a TRUNCATE before a INSERT will usually lead to only one row being available in the table, which seems like a weird use case for actually using a table.
You could use TRUNCATE TABLE and then your next query:
$cSQLt = "TRUNCATE TABLE CALIFICA_APTO";
$cSQLi = "INSERT INTO approved (ID_STUDENT, YEAR, APPROVED)
VALUES (
'" . $_POST['NSTUDENT'] . "',
'" . $_POST['YEAR'] . "',
'YES'
)";
$Connect->query($cSQLt);
$Connect->query($cSQLi);
If your looking to remove all of the data from a table you should use TRUNCATE:
TRUNCATE TABLE approved
Then you can do your SQL statement.
NOTE: This will delete all data from the table, so be careful! Also, your database user must have the ability to truncate tables.
I am trying to insert data into a table, and the data is drawn from another table. At the moment my code looks like this:
$result3 = mysql_query('SELECT order_no
FROM orders
WHERE ord_date = "' . ($_POST["ord_date"]) . '"');
while($row=mysql_fetch_array($result3)){ $order=$row['order_no'];}
$result4 = mysql_query('SELECT door_product_no
FROM estimateDescribesDoorProduct
WHERE estimate_no = "' . ($_GET["estimate_no"]) . '"');
while($row=mysql_fetch_array($result4)){ $door=$row['door_product_no'];}
$result5 = mysql_query('SELECT quantity
FROM estimateDescribesDoorProduct
WHERE estimate_no = "' . ($_GET["estimate_no"]) . '"');
while($row=mysql_fetch_array($result5)){ $dquantity=$row['quantity'];}
$sql2="INSERT INTO orderConsistsOfDoor (order_no, door_product_no, product_quantity)
VALUES ('$order','$door','$dquantity')";
I used this method yesterday thanks to some advice on this site. My problem today is that I need to insert multiple rows. The tables 'orderConsistsOfDoor' and 'estimateDescribesDoorProduct' are identical except that for the first column (order_no/estimate_no). Basically if an estimate (or order) consists of e.g. 3 products, then there will be 3 rows in the table with that estimate_no (but different product_no and quantity).
I think that the code I have will only insert one row into orderConsistsOfDoor, but I need it to insert every row where the estimate_no is ($_GET["estimate_no"]). I think this can be done with foreach or something but I've never used this and don't know how it works.
Can somebody help me?
To insert multiple records with one query, you can do:
INSERT INTO `table_name` (`foo`, `bar`) VALUES (1, 2), (3, 4), (5, 6);
See INSERT Syntax
You should use a library, though, it's 2012!
I'am trying to implement a "most popular searches" function on a web site using a simple counter. The idea is that the first time a search is made, the query is stored in a special table. After that the count number increments by one every time that same search is made. I think I do exactly as I should but the code doesn't seem to work. The count value stays on NULL in the table. Here's my code. "Searchny" is the table where I store the searches. Any pointers much appreciated!
$search_result = mysql_query("SELECT * FROM searchny WHERE sok='$sokt'");
if(mysql_num_rows($search_result) == 0 ) {
$sql = "INSERT INTO searchny (sok, dt) VALUES ('" . $sokt . "', NOW());";
mysql_query($sql);
}
else {
mysql_query("UPDATE searchny SET count = count+1 WHERE sok='$sokt'");
}
Probably your count column is NULL by default and every count+1 doesn't make it any less NULL. Try either setting default value of one or explicitly set it to one in INSERT.
Your code has no mistake, so the problem isn't the code.
Is your value NULL or 0 ?
If it is NULL, change
INSERT INTO searchny (sok, dt) VALUES ('" . $sokt . "', NOW());
to
INSERT INTO searchny (sok, dt, count) VALUES ('" . $sokt . "', NOW(), 0);
Your problem is most likely that count is NULL. Anything added to NULL is NULL.
Try this query:
SELECT NULL + 1
The result will be:
NULL
You could set your default value for the count field to 0 instead.
However, here's a simpler way to implement this. Note that I've excluded the date field because I don't know what the requirements for the date are:
Table searchny:
---------
sok
count
---------
primary_key (sok)
Then do it all in one statement:
INSERT INTO searchny (sok, count) VALUES ($sokt, 1)
ON DUPLICATE KEY UPDATE count = count + 1
If it's a new sok value, then a new row is inserted and the count is set to 1. If the sok value already exists, then the record's count is incremented by 1.