I know that this is mysqli, but im wondring how to get this query correct.
I want to insert username, besvarelse and modulid into table.
but if besvarelse is empty or null i want to write back message that its allready delivered.
$sql = "INSERT INTO oppgave(username, besvarelse, modulid)
select '$username', '$besvarelse', '$modulid'
from dual
where not exists (select modulid from oppgave where modulid='$modulid')";
$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
echo "<h1>Allready delivered</h1>";
}else{
echo "<h1>Delivery ok</h1>";
}
?>
//«if besvarelse is empty or null i want to write back message that its allready delivered.»
//To check besvarelse we shold not use SQL, it is much better to check it with PHP
if ($besvarelse=='' or is_null($besvarelse)) {
$resp = "<h1>Allready delivered</h1>";
} else {
$sql = ......;
$result=mysql_query($sql, $tilkobling);
if(mysql_affected_rows()==0){
$resp="<h1>Allready delivered</h1>";
}else{
$resp="<h1>Delivery ok</h1>";
}
echo $resp;
Related
i am trying to insert a data. But i am getting an error and i can't solve it any help will be really appreciated
Error: Warning: mysqli_num_rows() expects parameter 1 to be
mysqli_result, boolean given
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error());
if ($insert_qryy->num_rows==0)
{
echo "Error";
}
else
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`(`purpose`, `property_type`, `city`, `title`, `description`,
`property_price`, `land_area`, `expires_after`, `property_img`) VALUES('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."',
'".$landarea."','".$expiry."','".$im."')") or die (mysqli_error());
}
it is entering the $insert_qryy data but the second statement is not working If statement is getting false i hope I'll get my solution here
As you said - No i want to insert the data of second query if first query have inserted its data.check this once:-
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if ($insert_qryy)
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
} else{
echo "First Insert not executed properly";
}
Note:- Problem is Insert query return a boolen value true or false, based on query executed or not. So you can not use it directly in mysqli_num_rows(), because it ask for a result-set object as parameter not a boolean value.
For checking INSERT query status you can use mysqli_affected_rows or mysqli_insert_id().
$lastid = mysqli_insert_id($link);
Modified example:
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob)
values ('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr. "','".$country."','".$dob."')")
or die(mysqli_error());
$lastid = mysqli_insert_id($con);
if (intval($lastid) <= 0)
{
echo "Error";
}
else{
// your second query or success.
}
Use mysqli_affected_rows () function to check if data is inserted successfully into table
$insert_qryy = mysqli_query($con,"Insert into user_register(name,email,phone,cphone,address,city,country,dob) values('".$name."','".$email."','".$phone."','".$cphone."','".$address."','".$cityr."','".$country."','".$dob."')")or die(mysqli_error($con));
if (mysqli_affected_rows() > 0) //use this to check if data is inserted successfully into table
{
$handler = mysqli_query($con,"INSERT INTO `addproperty`( `purpose`, `property_type`, `city`, `title`, `description`,`property_price`, `land_area`, `expires_after`, `property_img`) VALUES ('".$purpose."','".$type."','".$city."','".$title."','".$desc."','".$price."','".$landarea."','".$expiry."','".$im."')") or die (mysqli_error($con));
}
else
{
echo "something went wrong!!! at first query insertion";
}
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
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;
My query inserts the data in to the record but it also display query failed. It inserts the record into the database, but instead of redirecting to the calander page it display query failed.
//Create INSERT query
$qry = "INSERT INTO `customer`(`login_id`,`firstname`, `lastname`, `ad1`, `ad2`, `ad3`, `postcode`, `phone`, `email`) VALUES ('{$_SESSION['SESS_LOGIN_ID']}','{$_SESSION['SESS_FIRST_NAME']}','{$_SESSION['SESS_LAST_NAME']}', '$ad1', '$ad2', '$ad3', '$postcode', '$phone', '{$_SESSION['email']}');";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
//Create query
$qry="SELECT user.login_id, customer.customer_id, customer.email FROM user, customer
WHERE user.login_id = customer.login_id AND customer.login_id= .'{$_SESSION['SESS_LOGIN_ID']}'.";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$login = mysql_fetch_assoc($result);
$_SESSION['SESS_CUSTOMER_ID']= $login['customer_id'];
$_SESSION['SESS_CUSTOMER_EMAIL']= $login['email'];
session_write_close();
header("location: calendar.php");
exit();
}
} else {
die("Query failed");
}
}
Your INSERT query is successful but the subsequent SELECT fails because it has a syntax error. When using the {} syntax in strings, don't use the concatenation . character.
Change to
$qry="SELECT user.login_id, customer.customer_id, customer.email FROM user, customer WHERE user.login_id = customer.login_id AND customer.login_id= '{$_SESSION['SESS_LOGIN_ID']}'";
Or concatenate without the {} syntax:
$qry="SELECT user.login_id, customer.customer_id, customer.email FROM user, customer WHERE user.login_id = customer.login_id AND customer.login_id= '" . $_SESSION['SESS_LOGIN_ID'] . "'";
If this query fails:
$result=mysql_query($qry);
Then the next line:
if($result) {
will result in the else bit being used i.e.
die("Query failed");
So check of errors in your SELECT statement.
You've got an extra dot in your second query:
Here
|
|
v
WHERE user.login_id = customer.login_id AND customer.login_id= .'{$_SESSION['SESS_LOGIN_ID']}'.";
A couple of thing to point out here:
You should not be using mysql_* functions as they are deprecated. You should look at using mysqli or PDO
There is no reason at all for your second SELECT query. You already just inserted all that information into the table. You only thing new is the login_id, which I am assuming is an autoincrement field. You can get this after the first query by simply calling mysql_insert_id()
Your original problem is that you are likley getting an SQL syntax error here:
$qry="SELECT user.login_id, customer.customer_id, customer.email FROM user, customer WHERE user.login_id = customer.login_id AND customer.login_id= .'{$_SESSION['SESS_LOGIN_ID']}'.";
Note that your periods and single quotes are going to be literally included in the string. You should use:
$qry="SELECT user.login_id, customer.customer_id, customer.email FROM user, customer
WHERE user.login_id = customer.login_id AND customer.login_id = {$_SESSION['SESS_LOGIN_ID']}";
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.