I have a web application in which students are divided into "batches".
I am trying to insert student for particular batch and the batch will be chosen by user by select option. After that student is added to the particular batch, he/she will be added to stdhold table. However, it is only inserting for the first selected value of select option.
<?php
function specialCOn() {
$connew = mysqli_connect("localhost","root","");
$db = mysqli_select_db($connew,'mcqs');
return($connew);
}
if (isset($_POST['add']))
{
$namestd=$_POST['std_name'];
$batchstd=$_POST['batch'];
$FNAME=$_POST['f_name'];
$query3 = "INSERT INTO `$batchstd` VALUES('','$namestd','$FNAME')";
$rsq3 = mysqli_query(specialCOn(),$query3);
mysqli_close(specialCOn());
$queryrollno = "select rollno from `$batchstd` order by rollno desc";
$rsqrollno = mysqli_query(specialCOn(),$querrollno);
$getrollno = mysqli_fetch_array($rsqrollno);
$rollnoto = $getrollno[0];
echo "<script>alert('$batchstd')</script>";
echo "<script>alert('$rollnoto')</script>";
mysqli_close(specialCOn());
//Problem is here
$querystdhold = "INSERT INTO stdhold VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd')";
$rsqhold = mysqli_query(specialCOn(),$querystdhold);
mysqli_close(specialCOn());
if ($rsq3&&$rsqhold)
{
echo "<script> alert('Student Added.');
window.location.assign('addstudent.php');
</script>";
//header('Location:addstudent.php');
}
else
{
echo "<script> alert('You Havenot added Student.');
window.location.assign('addstudent.php');</script>";
}
}
?>
Try use this :
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("INSERT INTO ? (col1,col2,col3) VALUES('',?,?)");
$stmt->bind_param('sss', $_POST['batch'], $_POST['std_name'], $_POST['f_name']);
$stmt->execute();
For the detail example you need to read the #Amber Answer how to create secured prepared statement.
Hope this'll help you.
Try specifying the column names in your insert query:
INSERT INTO stdhold (col1, col2, col3, col4) VALUES ($rollnoto, '$namestd', '$FNAME', '$batchstd');
For reference see the MySQL Insert documentation.
Related
I have a problem with SQL syntax. I have 2 tables and the third table is generated in SQL Workbench (n:m relationship).
My 3rd table has 2 columns product_id and categories_id.
I use this SQL in php my admin to add a new row:
INSERT INTO `products_has_categories` (`products_id`, `categories_id`)
VALUES ('17', '1');
if phpmyadmin, the sql add a new row, with product_id = 17 and categories_id =1.
My problem:
i have a simple php file called test.php looking like:
$connection = mysqli_connect("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
}
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1');";
or
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')";
When i run test.php file, the code not working, and no adding new row in SQL table.
Can u help me?
As far I'm concerned, you're not even calling query().
Try this:
$connection = new mysqli("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
} else {
$query = $connection->query("INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')");
}
I have this php file to deal with my sql, I want to make many statement on one record in the database
for examole I have this query :
$query = mysql_query("SELECT bloodGroup,quantity,bank_id FROM medical_bank_notification WHERE seen=1");
I want to make all the records which were selected in the $query to have the field seen=0 after it has been selected, so I thought that I have to know all the IDs from the first query and then write another query:
$sql2 = "INSERT INTO medical_bank_notification (seen) VALUES (0) WHERE ID=_????_";
use mysqli_multi_query($con,$query)
$query = "INSERT INTO table1 (column1,column2,column3)
VALUES (value1,value2,value3);";
$query .= "INSERT INTO table2 (column1,column2,column3)
VALUES (value1,value2,value3);";
//excute query
if(mysqli_multi_query($con,$query))
{
while (mysqli_next_result($con) && mysqli_more_results($con))
{
if ($resSet = mysqli_store_result($con)) { mysqli_free_result($resSet); }
if (mysqli_more_results($con)){ }
}
echo 'success';
}
I have the following two queries. Second query is dependent on first one.
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
$message = "both queries executed successfully";
}
else
{
$del = mysql_query("delete record inserted by $query1");
}
}
Can we execute these two queries in a single statement so that both queries depend on each other.If INSERT query fail, DELETE query also fail it's execution as well as if DELETE query fail INSERTION in query first fail.
Thanks
If I good understand what you need, simply use transactions.
Run this query before your insertion:
mysql_query('begin');
And then, if everything went fine, commit the transaction:
mysql_query('commit');
In case of any failures, you may rollback every change you made:
mysql_query('rollback');
Note that in case of MySQL, the MyISAM engine does not support rollback in transactions, so use InnoDB.
Read more about transactions here: https://dev.mysql.com/doc/refman/5.0/en/commit.html
Example with your code:
<?PHP
mysql_query('begin'); //start transaction
$query1 = mysql_query("Insert into table_one set ---- ");
if($query1)
{
$query2 = mysql_query("delete from table_two where condition---");
if($query2)
{
mysql_query('commit'); //both queries went fine, so let's save your changes and end the transaction
$message = "both queries executed successfully";
}
else
{
mysql_query('rollback'); //query2 failed, so let's rollback changes made by query1 and end the transaction
}
}
else
mysql_query('rollback'); //query1 failed, so let's end the transaction
If query2 fails it doesn't check query1.
$query1 = mysql_query("Insert into table_one set ---- ");
$query2 = mysql_query("delete from table_two where condition---");
if( $query2 && $query1)
{
$message = "both queries executed successfully";
}
else if(!$query2)
{
$del = mysql_query("delete record inserted by $query1");
}
You can use transaction, if any query fails then call rollback, otherwise commit
I found a best solution.
Extending idea of #Luki i wrote the following code and it give me too much satisfied answer. First use the following function.
function multi_statement()
{
global $conn;
$total_args = func_get_args();
$args = implode($total_args,";");
$args = "begin;".$args.";commit;";
$number = 0;
if($conn->multi_query($args))
{
do
{
if ($conn->more_results())
{
$number++;
}
}
while($conn->next_result());
}
if($number < (count($total_args)+1))
{
$conn->query('rollback');
echo "Sorry..!!! Error found in Query no:".$number;
}
else
{
echo "All queries executed successfully";
}
}
Then I called the function with number of statements, all these statements are dependent on each other. In-case there is error in any query, no one query occur any changes in database.
$statement1 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as1', 'as1')";
$statement2 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as2', 'as2')";
$statement3 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as3', 'as3')";
$statement4 = "INSERT INTO `pic_gall`.`admin` (`admin_id`, `username`, `password`) VALUES (NULL, 'as4', 'as4')";
$statement5 = "DELETE from user where user_id = '12'";
multi_statement($statement1,$statement2,$statement3,$statement4,$statement5);
simply put my code doesn't seem to be working probably the variables work and echo out its simply the code for insert im doing wrong no error just doesnt insert into the table.. the idea is that it inserts in to a table and replaces the data already in the id selected
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "INSERT INTO `tblas`(`id`, `question`, `A`, `B`, `C`, `D`, `correct`) VALUES ([".$idbox."],[".$questionbox."],[".$boxA."],[".$boxB."],[".$boxC."],[".$boxD."],[".$correctbox."])";
$editquery= mysql_query($sql2, $db);
echo $editquery;
try this query instead of insert query
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "UPDATE tblas SET id='".$idbox."', question = '".$questionbox."', A = '".$boxA."', B = '".$boxB."' ,C = '".$boxC."', D= '".$boxD."' , correct= '".$correctbox."'";
}
echo $editquery;
I've looked around nothing seems to be working for me. I have a button when pushed it INSERTS data into 1 table-1, then it gets values from table-3 to put in table-2 where in they the ID is the same.
if ($movieTime != "") {
$query = "SELECT SchedID FROM tblCinemaSched WHERE TheaterID='$tid' AND CinemaID='$cid' AND MovieDate='$date' AND MovieTime='$movieTime'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$numRows=$conn->numRows($result);
if ($numRows<=0) {
$query = "INSERT INTO tblCinemaSched SET TheaterID='$tid', CinemaID='$cid', MovieDate='$date', MovieTime='$movieTime', MovieID='$movieId', PriceAmt='$priceId', CrtBy='$username', CrtDate=NOW()";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
//get seat defaults from tblCSeats
$query = "INSERT INTO tblSSeats SELECT TheaterID, CinemaID, '$date', '$movieTime', SeatID, RowNo, ColumnNo, Handicap, Status, LeftSeat, RightSeat, NULL, NULL,NULL,NULL,NULL,NULL,NULL,'$username',NOW() FROM tblCSeats WHERE TheaterID='$tid' AND CinemaID='$cid'";
//echo "$query<br>";
$result=$conn->executeUpdate($query);
$errorStr = "Succesfully added schedule.";
}
else {
$errorStr = "There's already an existing schedule for the specified time.";
}
You see tableCSeats has more than 1 row that has the same ID meaning I want to insert multiple data from tableCSeats to tableSSeats. tableSSeats is a has no data in it yet.
At a blind guess, it would seem that you are looking for INSERT ... SELECT statement.
check the return values of your queries. You always get "Succesfully added schedule." because you don't check if the queries were succesful. Ex:
if(!$result=$conn->executeUpdate($query)) {
die('error');
}
or something like that.