Error inserting two query in once by php - php

I'm trying to insert data in two tables, with exploiting the the primary key of the first one and add it as foreign key in the second table,i think the problem is the two query are inserting each info in the same time and it give us a conflict between foreign key and primary one,any ideas ? maybe making something like a delay between each query !!
<?php
$InputCIN = filter_input(INPUT_POST,"CIN");
$InputID_PAYEMENT = filter_input(INPUT_POST,"ID_PAYEMENT");
$InputDATE_PAYEMENT = filter_input(INPUT_POST,"DATE_PAYEMENT");
$InputTYPE_DE_PAYEMENT = filter_input(INPUT_POST,"TYPE_DE_PAYEMENT");
$InputPRIX = filter_input(INPUT_POST,"PRIX");
$InputMOIS_PAYEMENT = filter_input(INPUT_POST,"MOIS_PAYEMENT");
$queryAj2_1 = "insert into payement values($InputID_PAYEMENT,'$InputDATE_PAYEMENT','$InputTYPE_DE_PAYEMENT',$InputPRIX,'$InputMOIS_PAYEMENT')";
$queryAj2_2 = "insert into payer values('','$InputCIN',$InputID_PAYEMENT)";
if(isset($_POST['butAj2']))//submit button
{
if($InputID_PAYEMENT && $InputCIN)
{
if(mysqli_query($con,$queryAj2_1) && mysqli_query($con,$queryAj2_2))
{
$msg = "<div class='alert alert-success'><span class='fa fa-square-check'></span>Adding successfull</div>";
}
else
{
$msg = "<div class='alert alert-danger'><span class='fa fa-square-check'></span>Erorr adding</div>".mysqli_error($con);
}
}
else if(!$InputID_PAYEMENT && !$InputCIN)
{
$msg = "<div class='alert alert-danger'><span class='fa fa-square-check'></span>ADD CIN/ID PAYEMENT</div>".mysqli_error($con);
}
else{
$msg = "<div class='alert alert-danger'><span class='fa fa-square-check'></span>erorrrrrrrrrrrrr</div>".mysqli_error($con);
}//it show me this msg
}
>

The mysqli_multi_query() function performs one or more queries against the database.
The queries must be separated with a semicolon.
from php.net
MySQL optionally allows having multiple statements in one statement
string. Sending multiple statements at once reduces client-server
round trips but requires special handling.
Multiple statements or multi queries must be executed with
mysqli_multi_query(). The individual statements of the statement
string are separated by semicolon. Then, all result sets returned by
the executed statements must be fetched.
The MySQL server allows having statements that do return result sets
and statements that do not return result sets in one multiple
statement.
$queryAj2_1 = "insert into payement values($InputID_PAYEMENT,'$InputDATE_PAYEMENT','$InputTYPE_DE_PAYEMENT',$InputPRIX,'$InputMOIS_PAYEMENT');";
$queryAj2_2 = "insert into payer values('','$InputCIN',$InputID_PAYEMENT)";
// Execute multi query
if (mysqli_multi_query($con, $queryAj2_1. $queryAj2_2))
{
// print message on success
Use of the multiple statement with prepared statements is not supported.

There is been conflict when you are trying to execute both the query at the same time. The 2nd table does not able to take the reference of the 1st tables primary key.
Try this out....
if(mysqli_query($con,$queryAj2_1))
{
if(mysqli_query($con,$queryAj2_2))
{
$msg = "<div class='alert alert-success'><span class='fa fa-square-check'></span>Adding successfull</div>";
}
}
So, here there will be no chance of conflict and primary key will be inserted first into the table and then it's foreign key.

You can Try the code below to fire multiple query in PHP.
$sql = "INSERT INTO requestdetails (`userid`, `dayte`) VALUES ('$userid','$date');INSERT INTO managerrepo (`userid`, `dayte`) VALUES ('$userid', '$date') ";
if($conn->multi_query($sql) === TRUE)
{
echo "You have requested successfully!";
unset($_POST);
//header("location: index.php?id=".$id);
}
else
{
echo "Problem in request. Try Again!";
}
OR
you use the below code too, for insertion in same table:
$sql = "INSERT INTO requestdetails (`userid`, `dayte`) VALUES ('$userid','$date')";
$sql_new = "INSERT INTO requestdetails (`userid`, `dayte`) VALUES ('$userid', '$date') ";
if($conn->multi_query($sql) === TRUE)
{
if($conn->multi_query($sql_new) === TRUE)
{
}
else
{
echo "error";
}
}
else
{
echo "Problem in request. Try Again!";
}

Related

How to replace username with link in string?

I'm trying to check posts to see whether they mention another user, by using #username. I want to replace that with a link to the user's profile.
This is what I've got... I haven't got any errors, but usernames just go through as text without the link. I feel like $getUsers/$gU isn't returning the results to $checkString, but I can't see anything wrong.
function post()
{
global $me;
if($_POST['message'])
{
$getUsers = mysql_query("SELECT user_id, user_name FROM users");
while($gU = mysql_fetch_array($getUsers))
{
$checkString = strpos($_POST['message'], "#".$gU['user_name']."");
if($checkString !== false)
{
$replaceFrom = "#".$gU['user_name']."";
$replaceTo = "<a href=\'/user.php?id=".$gU['user_id']."\'>".$gU['user_name']."</a>";
$checked = str_replace($replaceFrom, $replaceTo, $_POST['message']);
}
else
{
$checked = $_POST['message'];
}
}
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
index();
}
else {
echo "
<form action='?action=insert' method='post'>
<input type=text name=topic maxlength=40>
<br><textarea name=message cols=80 rows=9></textarea>
<br><input type='submit' STYLE='color: black; background-color: white;' value='Submit' class='btn'>
</form>
";
}
}
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$_POST['message']."', UNIX_TIMESTAMP())");
should be
mysql_query("INSERT INTO test_table VALUES ('', '".$me['user_id']."', '".$_POST['topic']."', '".$checked."', UNIX_TIMESTAMP())");
As your user table will eventually grow, I'd suggest compiling a set of potential usernames by searching for #(\w+), preparing a statement looking for that username, iterating through the results and replacing all instances for every returned row with the link.
I think you could have simplify your question by excluding the MySQL part. From what I understand you are trying to replace user mention with an HTML anchor tag.
Instead of looping through all the available users you can use preg_replace_callback() to check if any tagged user exists in system.
Please review the example code below. To simplify things I have created two functions. parseTag() will inject the HTML anchor link if the user exist, otherwise the original tag will be kept. getUserId() will return the user id it exists in the system instead:
<?php
function parseTag($tagInfo){
list($fullTag, $username) = $tagInfo;
$uid = getUserId($username);
if ($uid) {
return "<a href='/url/to/user/{$uid}'>{$fullTag}</a>";
}
return $fullTag;
}
function getUserId($username){
$userList = [null, 'john', 'mary'];
return array_search($username, $userList);
}
$comment = "Hello #john, #doe does not exists";
$htmlComment = preg_replace_callback("/#([\w]+)/", "parseTag", $comment);
echo $htmlComment;
Output:
Hello <a href='/url/to/user/1'>#john</a>, #doe does not exists

PHP echo break tag

In my PHP script, there are 3 echo, based on the conditionals
echo "Error"
echo "User already existed"
echo "Success"
One of the echo will be passed to my android apps, if (s.equals("Success")), where s is the echo message.
But the echo I got when the registration success is <br />, according to the logcat. For User already existed have no problem.
Since s is not Success, I can't start another activity which is depended on the string. Can anyone explain how the break tag got echoed? The registration information successfully inserted into database, though.
elseif ($roleID == "C") {
$sql6 = "SELECT runnerID FROM tr_customer WHERE customerID = '$newID'";
$check4 = mysqli_fetch_array(mysqli_query($con,$sql6));
if(!isset($check4)) {
// add into db
$customerID = $roleID . $newID;
$sql7 = "INSERT INTO tr_customer(customerID, name, phoneNo, locationID, roleID, email) VALUES ('$customerID', '$name', '$phoneNo', '$locationID', '$roleID', '$email')";
if(mysqli_query($con,$sql7)) {
echo "Success";
}
} else {
$newID = checkExist();
}
I would examine the code where the variable is defined. If you could post that part of the code as an edit then perhaps someone can review it for you as well. There is just not enough information here to discern where your error is coming from.
EDIT:
Consider changing the way you check for a successful update.
$result = mysqli_query($con,$sql7);
if(mysqli_num_rows($result) == 1){
echo "Success";
}

Wrong part of if statement being executed

When I delete a record from table, I have 8 columns in the table and if more than 8 is entered it must be showed that nothing was deleted. However every number that I give, I get the same response "deleted successfully". This is my code:
$query = "DELETE FROM `order` WHERE orderId = '$_POST[id]'" ;
$result = mysql_query($query);
if(! $result )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
$result will be a valid result, even when your query won't affect any rows. Use mysql_affected_rows() to check if you deleted anything.
$result = mysql_query($query);
if( mysql_affected_rows() == 0 )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
side note: the mysql_* functions are deprecated. Don't use them to write new code, especially when you are learning. Use mysqli_*or PDO instead.
You can use mysql_affected_rows
$query = "DELETE FROM `order` WHERE orderId = {$_POST[id]}" ;
mysql_query($query);
if(0 == mysql_affected_rows()){
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}else{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
You are testing if your query ran successfully. It can be successful if it deletes one row or if it deletes none.
Use mysql_affected_rows to determine if you've deleted any rows.
(You'd be better moving to a more modern API though)

nested insert into two tables

I have the code below. I take with post some variables from another page. Then I run my query and I store them to the table materials. Then I select for this table in order to take materialsid and then I want with insert into to store the value of materialsid in another table called material_damages
<?php
session_start();
if(isset($_POST['submit'])) {
include('dbConfig.php');
$mname1=$_POST['name1'];
$mcost1=$_POST['cost1'];
$mquantity=$_POST['quantity'];
$res=mysql_query("INSERT INTO materials VALUES (NULL, '$mname1', '$mcost1','$mquantity')");
if ($res)
{
echo "Insert successful";
}
else
{
echo "Insert failed";
}
$res1=mysql_query("SELECT * FROM materials");
while ($row = mysql_fetch_array ($res1))
{
$id10=$row['materialsid'];
$id11=(int)$id10;
$res2=mysql_query("INSERT INTO damage_materials (damage_materials_id,damage_id,materials_id) VALUES (NULL,NULL,'$id11')");
if($res2)
{
echo "CORRECT";
}
else
{
echo "FALSE";
}
}
}
?>
The material is stored at table materials but the id does not get stored in the table damage_material. It prints Insert succesful FALSE FALSE FALSE FALSE (false is as the number of my materials)
Any ideas?

Not inserting where i expected

In a mysql table, i have 3 fields. user_to, user_from and id. The variables are all correct and should be inserting the correct data.
When a button is clicked, named 'poke', it should insert the cookie that stores the session of who did it and the person who was poked. It doesn't seem to be inserting and I am stuck :(
$cookie = $_SESSION['user_login'];
//Poke code
if (#$_POST['poke']) {
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$username' && user_from='$added_by'");
$num_poke_found = mysql_num_rows($check_if_poked);
if ($num_poke_found == 1) {
echo "Come on! Give the guy a chance!";
}
else
if ($username == $cookie) {
echo "You cannot Jab yourself.";
}
else
{ $poke_user = mysql_query("INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')") or trigger_error(mysql_error());
echo "$username has been jabbed.";
}
}
You used wrong quotes with fields in MySQL query.
//your wrong variant
"INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')"
//right variant
"INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$cookie', '$username')"
Quotes like ' mean values and quotes like ` mean fields in SQL syntax
<?php
if ($_POST['poke']) {
#ref to the current user
$from = $_SESSION['user_login'];
#ref to the (poked user)
$to = $_POST['poked_user_id'];
if($from == $to){
echo "you cant poke yourself!";
}
else{
#ADVICE: USE PDO OR MYSQLI INSTEAD OF MYSQL
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$to' AND user_from='$from'");
if(mysql_num_rows($check_if_poked)){
echo "Come on! Give the guy a chance!";
}
else{
if(mysql_query("INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$from', '$to')")){
echo "$to has been jabbed.";
}
else{
trigger_error(mysql_error());
}
}
}
}
?>
This started off as a comment - but it's getting too long to fit.
A session is not the same thing as a username - your post is very confused.
Leaving aside the wrong quotes (which is why your code is not doing what you expect)....
In a mysql table, i have 3 fields. user_to, user_from and id
... in that case you don't need to check if the row already exists - and not create duplicates. Set up a unique index then...
if (#$_POST['poke'] && ($_SESSION['user_login']!===$username)) {
$qry = "INSERT INTO `pokes` (`user_from`, `user_to`)
VALUES (".mysql_real_escape_string($_SESSION['user_login'])
.", '" . mysql_real_escape_string($username) . "')"
if (mysql_query($qry)){
echo "$username has been jabbed.";
} else if (stristr(mysql_error(), 'duplicate')) {
echo "Come on! Give the guy a chance!";
} else {
echo "It's all gone Pete Tong!";
}
} else if ($_SESSION['user_login']!===$username) {
echo "You cannot Jab yourself.";
}
While it's about the same effort for PHP processing, the DB workload is significantly less. This code also prevents some SQL injection attacks, and has error handling. I presume that $username has been created elsewhere and you don't have register_globals enabled.

Categories