$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
} else {
$check1='fail';
}
when i run this php only the first sql statement is inserted.
How can i make the second sql statement run when i inserted into the first sql statement?
As #Darren pointed out, you're not actually executing the statement, you're just updating the value of $sql.
$sql = "INSERT INTO nextofkin(username,password,contact,email) VALUES('$NOKUN','$NOKPW', '$NOKContact', '$NOKEmail')";
if ($conn->query($sql) === TRUE) {
$sql = "INSERT INTO users(username,password,role) VALUES ('$NOKUN','$NOKPW', 'nextofkin')";
$conn->query($sql);
} else {
$check1='fail';
}
Related
I've seen a few posts dealing with UPDATE statements in MySQL, but none of them seem to apply to my specific situation.
I have the following code:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
Essentially, I'm trying to check to see if an entry exists. If it exists, then update it. If the entry doesn't exist, then make it.
The INSERT statement executes perfectly. However, the UPDATE statement does nothing. There is no error message, and no changes made in my table.
Any ideas?
Thanks!
As Forbs stated, your UPDATE statement will not result in any changes since you are filtering based on "current_timestamp", which will be whatever time the query executes. What you need to do instead is pass an existing timestamp into your code so that it updates whatever existing record already has that as its iso_date.
See the example below for how you can change your code.
//this is whatever your time is that you are looking for a record for
$isoDateDT = '2018-08-01 08:15:00';//human readable datetime
$isoDateTS = strtotime($isoDateDT);//unix timestamp
$result = "SELECT * FROM open_lab_report WHERE iso_date = $isoDateTS";
if(!mysqli_query($link, $result)) {
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES ($isoDateTS, '$lab_monitor', 1)";
} else {
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = $isoDateTS";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
You have to correct your if statement checking.
In your Case you can count number of entries with same timestamp as current timestamp.
and then
if count<1 then you can UPDATE ,otherwise INSERT.
EXAMPLE:
$result = "SELECT iso_date FROM open_lab_report WHERE iso_date = current_timestamp";
$row=mysqli_num_rows(mysqli_query($link, $result))
if($row<1){
$sql = "INSERT INTO open_lab_report (iso_date, lab_monitor, incidentReport) VALUES (current_timestamp, '$lab_monitor', 1)";
}else{
$sql = "UPDATE open_lab_report SET incidentReport = 1 WHERE iso_date = current_timestamp";
}
if(!mysqli_query($link, $sql)) {
echo "Query failed, code: " . mysqli_errno($link);
}
$allgames = file_get_contents("https://steamspy.com/api.php?request=all");
$decodeall = json_decode($allgames, true);
foreach($decodeall as $game) {
$sql = "INSERT INTO games (name)
VALUES ('{$game['name']}')";
}
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
When i do this only the first row will be added. How do i insert multiple rows?
Just get rid of that multi query thing. Use a prepared statement instead
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach($decodeall as $game) {
$name = $game['name'];
$stmt->execute();
}
echo "New records created successfully";
Note that your current code with multi_query won't work as intended anyway, even with that silly typo fixed. You will have the result of only first query, having no idea what happened to all others.
You are overwriting the query each time. Try setting sql to blank then appending it each time in the loop.
Try this:
$sql = array();
foreach($decodeall as $game) {
$sql[] = "INSERT INTO games (name) VALUES ('{$game['name']}')";
}
$sqlInserts = implode(';', $sql);
if ($conn->multi_query($sqlInserts) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You don't need to perform the query multiple times like that, you can do it all in a single query without multi_query(). You can perform many INSERTs with a single query, like this
// Initialize the query-variable
$sql = "INSERT INTO games (name) VALUES";
// Loop through results and add to the query
foreach ($decodeall as $game) {
$sql .= " ('".$game['name']."'),";
}
// Remove the last comma with rtrim
$sql = rtrim($sql, ',');
// Perform the query
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will generate a query resembling
INSERT INTO games (name) VALUES ('One'), ('two'), ('Three')
which will insert the values One, Two and Three into separate rows.
This query will break if your $game['name'] variables contain an apostrophy ', so at the very least you should use $mysqli::real_escape_string(), although a prepared statement takes care of that and prevents SQL injection (so I recommend you go for that instead). See How can I prevent SQL injection in PHP?
Using a prepared statement - the better solution
The preferred method of executing a query is by using a prepared statement.
Fetch all the columns using array_column() and loop the array while calling the execute method until finished.
$stmt = $conn->prepare("INSERT INTO games (name) VALUES (?)");
$stmt->bind_param("s", $name);
foreach (array_column($decode, "name") as $name) {
$stmt->execute();
}
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";
}
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);