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.
Related
I'm trying to check an email against my database, and if it doesn't already exist, add it to the database.
$query = "SELECT * FROM users";
$inputQuery = "INSERT INTO users (`email`,
`password`) VALUES ('$emailInput',
'$passInput')";
$emailInput = ($_POST['email']);
$passInput = ($_POST['password']);
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
if ($row['email'] == $emailInput) {
echo "We already have that email!";
} else {
mysqli_query($link, $inputQuery);
echo "Hopefully that's been added to the database!";
}
}
};
It can detect an existing email, it's just the adding bit...
Currently this seems to add a new empty row for each existing row (doubling the size).
I'm trying to understand why it doesn't add the information, and how to escape the loop somehow.
Also for good measure, everyone seems to reuse $query, but this seems odd to me. Is it good practice to individually name queries as I have here?
Please let me know if there's anything else I should add.
I am not going to talk about the standards but straight, simple answer to your question.
Approach - 1:
INSERT INTO users (`email`,`password`) SELECT '$emailInput', '$passInput' from DUAL WHERE NOT EXISTS (select * from users where `email` = '$emailInput');
Approach - 2:
- Create a unique key on email column
- use INSERT IGNORE option.
user3783243 comments are worth noting
Try this :
$emailInput = mysqli_real_escape_string($link, $_POST['email']);
$passInput = mysqli_real_escape_string($link, $_POST['password']);
$qry3=mysqli_query($link,"select * from users where `email`='".$emailInput."'");
$num=mysqli_num_rows($qry3);
if($num==1) {
echo "Email-Id already exists";
} else {
$inputQuery = mysqli_query($link,"INSERT INTO users (`email`, `password`) VALUES ('".$emailInput."', '".$passInput."')");
if ($inputQuery) {
echo "Hopefully that's been added to the database!";
}
}
Your code seems to be a bit over-engineered because why not to pass you $_POST['email'] to select query where clause
"SELECT * FROM users where email = $emailInput" and then check if it is there already.
Also, keep in mind that this is an example only, and you should always check and sanitize user input.
From another hand you can do it with MySQL only using INSERT ... ON DUPLICATE KEY UPDATE Syntax. https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
That requires to add unique key for email column.
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';
}
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 am trying to add an if statement to a mysql query so that it checks the user exists from a table called ptb_users in the user_id column before the query runs.
users can write on other users walls and before a user can write on a users wall / before the query inserts into ptb_wallposts, i want it to check that the from_user_id = the ptb_users.user_id.
i am trying to do this but i get syntax errors all over my page can someone please can someone show me how i would need to structure this:
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
if exists (select user_id from ptb_users where user_id = #id)
begin
{
$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} }
}
end
else
begin
echo "error user doesnt exist"
end
?>
Here's an example of if statement (from MySQL Reference)
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Let me explain a little more better, i'll compare between PHP and SQL if statements
PHP:
IF(variable > 0){
anything..
}
SQL:
IF variable > 0 THEN anything..
Read more:MySQL Reference - IF STATEMENT
I have been given a task to convert the hardcoded fields into dynamic fields.I have changed it partially to dynamic
Let me explain you the situation ,
We have a lot of databases and each database has a table by name Surveys
By using the DESCRIBE statement we will retrieve the fields in the Surveys table regardless of the database .
I need to know the way where we can loop again and again till all the fields in the survey table appears.
In the below code I have left the for loop blank .
Please let me know the changes that neeeds to be done to get this working
I would really appreciate any kind of help
function insertIntoUserUploadFileds() {
$describe="DESCRIBE surveys";
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
$inUse="0";
$type="";
//for(){
if($field=='type'){
$type="N";
}elseif(($field=='fname') || ($field=='lname') || ($field=='phone')){
$inUse="1";
$type="T";
}elseif($field=='email'){
$inUse="1";
$type="E";
}
//$sql .= "('".$field."', '".$inUse."', '0', '
$result1 = mysql_query ($describe);
$result = mysql_query ($sql);
//}
}
$result1 = mysql_query ('DESCRIBE surveys');
//here is how you retieve all field and check
while($row = mysql_fetch_array($result1)) {
$sql = "INSERT INTO `userUploadFields` (`fieldName`, `inUse`, `mandatory`, `type`, `mapTo`) VALUES";
//here you can do if else to check the column name
if($row['field']=='type')
{
$type="N";
}
else if(($row['field']=='fname') || ($row['field']=='lname') || ($row['type']=='phone'))
{
$inUse="1";
$type="T";
}
else ($row['field']=='email')
{
$inUse="1"
$type="E";
}
//build your query
$sql .= "('".$field."', '".$inUse."', '0', '......)
//execute your complete query
$result = mysql_query ($sql);
}//end of while
Instead of using DESCRIBE, if you are trying to retrieve the default type of a particular column you might look into this. It describes how to break down the information from a particular table. Codex