Multiple mysqli_query not executed in same connection without closing connection - php

I have an issue with the following statement. No error is produced but my second mysqli_query is not being executed. In my previous project, I was forced to close and reopen the connection to the database before executing a new query but I'd like to believe that it's not very smart to close and reopen connections to a database several times in a script. Is there a way to go around this ?
Secondly, I've included my connection script in a separate file. So, should I close it after the first mysqli_query, how do I reopen it to be able to execute the second(subsequent) mysqli_query? I've thought of creating my own function that'll reopen the connection but I want to stay away from opening and closing database connections several times in a single script if possible.
$query = "SELECT * FROM customer WHERE email = '$email'";
$data = mysqli_query($dbc, $query) or die (mysqli_error($dbc));
if (mysqli_num_rows($data) == 0){
$queryInsertMember = "INSERT INTO customer VALUES ('$email', '$name', '$surname', SHA('$confirmedPassword'), '$gender', '$telMobile')";
mysqli_query($dbc, $queryInsertMember) or die (mysqli_error($dbc));
$queryInsertAddress = "INSERT INTO address VALUES ('$email', '$hzNumber', '$streetName', '$suburb', '$city', '$postalCode', '$province' , '')";
mysqli_query($dbc, $queryInsertAddress) or die (mysqli_error($dbc));
} else {
echo 'member already exists';
}

Related

INSERT INTO Statement not working PHP/MySQLI

I've combed through this site non-stop looking for the solution to my problems but have come up empty handed still.
Here's the problem, whenever I use the following INSERT INTO statement nothing is inserted into my database, the code runs without a hitch but at the end of the day my database is still empty(excluding values I manually inserted myself).
I would also like to point out that I ran a SELECT FROM statement that returned manually inserted values from the database nicely.
Anyway here's the code:
Connecting to database
$link = mysqli_connect("localhost", "root", "", "prototype");
Insert code
if ($error) echo "There were error(s) in your signup details:".$error;
else
{
$query = "SELECT * FROM `users` WHERE email = '".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
echo $results;
if ($results) echo " This email address is already taken. Would you like to log in?";
else
{
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email']).', '.md5(md5($_POST['email']).$_POST['password'])."')";
mysqli_query($link, $query);
echo "You've been registered!";
$_SESSION['id'] = mysqli_insert_id($link);
print_r($_SESSION);
// Redirect to logged in page
}
Try to change your insert query as below
$query = "INSERT INTO `users`(`email`, `password`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."', '".md5(md5($_POST['email']).$_POST['password'])."')";

Problems with mysqli_query function [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 7 years ago.
i'm new to PHP and MySQL. I'm having issues with one of my mysqli_query functions. I have a database connection that works perfectly as the first half of my php file actually stores data into certain tables of the database.
The problem starts when i want to perform another query against the database. Here's the code:
// INSERT statements.
$queryMember = "INSERT INTO member (surname, name, gender, email, telHome, telMobile, dob, studentNum, idNum) VALUES ('$sur_name', '$f_name', '$gender', '$email', '$tel_home', '$mobile_num', ,'$date_of_birth', '$studentNumber', '$id_number')";
$queryAddress = "INSERT INTO physicalDetails (houseNum, unitNum, streetAdd, suburb, city, province, code ) VALUES ('$house_number', '$unit_number', '$street_address', '$suburb_name', '$city_name', '$province_name', '$zip_code')";
$queryStaff = "INSERT INTO staff (staffID ) VALUES ('$staff_id')";
$queryStudent = "INSERT INTO student (major ) VALUES ('$student_major')";
// Statements that must query the database.
$resultMember = mysqli_query($dbc, $queryMember) or die ('Error while inserting data into member details table');
$resultAddress = mysqli_query($dbc, $queryAddress ) or die ('Error while inserting data into member physical details table');
$resultStaff = mysqli_query($dbc, $queryStaff ) or die ('Error while inserting data into staff information table' );
$resultStudent = mysqli_query($dbc, $queryStudent ) or die ('Error while inserting data into student major details table');
mysqli_close($dbc);
When i run my form, my first error is the following: "Error while inserting data into member details table".
I don't understand why it's giving me an error. Any advice or suggestions would be appreciated. :)
Don't output a fixed (and useless) error message: Have the DB tell you what you did wrong:
$resultMember = mysqli_query($dbc, $queryMember) or die (mysqli_error($dbc));
^^^^^^^^^^^^
If you had that, you'd have been told about your syntax errors:
$queryMember = "[..snip..], '$mobile_num', ,'$date_of_birth', '$studentNumber', '$id_number')";
^^^^

mysqli_query not working as expected

I have the php:
$con=mysqli_connect("127.0.0.1","foo","bar","quaz");
if($con){
$sql = "INSERT INTO `virtual_users` (`domain_id`, `password` , `email`)
VALUES ('2', ENCRYPT('".$password."', CONCAT('\$6\$', SUBSTRING(SHA(RAND()), -16))), '".$user."#".$domain."');";
$query = mysqli_query($con, $sql);
if(!$query){
echo $sql;
}else{
echo "Success adding new email user!";
}
}
For some reason when I run this query it always returns $sql. This means that the connection is fine but the query is not.
When I then run the the echo of $sql directly on the mysql database it works perfectly!! I have no idea what is going wrong! Any ideas?
That's because you should be outputting the reason for the failure, not the query that caused the failure:
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
^^^^^^^^^^^^^^^^^^^^^^^^^^^
There's exactly ONE way for a query to succeed, and a near infinite number of ways for it to fail. Just having "valid" sql means nothing.

Can't insert data into mutiple mysql tables

So i've just started learning the basics of php and mysql and I was trying to use it to hold message and conversation data from a messaging app I am currently programming. So today I was just trying to test adding a message to the message table and record it in the conversation table but each time it adds the message, skips the conversation, and moves on. Any help would be much appreciated.
function addMessage($user, $recipient, $message, $status) {
require_once __DIR__ . '/db_config.php';
// attemp to connect to the server and database
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
exit("Error 01");
}
$query = "INSERT INTO Messages (Message) VALUES ('$message')";
$result = mysqli_query($db, $query);
$id = mysqli_insert_id($db);
$query2 = "INSERT INTO Conversations (User, Recipient, MeId, Status, Received)
VALUES ('$user', '$recipient', '$id', '$status', '0')";
$result = mysqli_query($db, $query2);
echo $result;
}
Just simply add or die(mysqli_error($error)); at the end of your query
Like:
$result = mysqli_query($db, $query2) or die(mysqli_error($error));
You can see now error log.
The PHP looks fine to me.
Is
echo $result;
returning '0'?
If so, there's a problem with you SQL statement somewhere, maybe field is named wrong or it is not following the structure. Hard for me to know without seeing your DB. Turn on error reporting and see if it spits out any errors.

Multiple INSERT not working

I have multiple If statements that if true, inserts data into the db. The Problem is that the 2nd one of the INSERT statements inserts it 4 times. How would i stop it from adding duplicates. Also the returned $_POST['tshirt'] contains only one value which is being inserted 4 times.
if(isset($_POST['distance'])) {
$dist = $_POST['distance'];
$sql="INSERT INTO sportevent_parameters.Distance(value, user_ref, event) VALUES ('$dist', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['tshirt'])) {
$tshrt = $_POST['tshirt'];
$sql="INSERT INTO sportevent_parameters.T_Shirt(value, user_ref, event) VALUES ('$tshrt', '$id', '$event') ON DUPLICATE KEY UPDATE";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['partnerid'])) {
$sql="INSERT INTO sportevent_parameters.Partner_ID(value, user_ref, event) VALUES ('$partnerid', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
if(isset($_POST['racecategory'])) {
$sql="INSERT INTO sportevent_parameters.Race_Category(value, user_ref, event) VALUES ('$category', '$id', '$event')";
}
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
What would cause it to insert multiple copies into the DB?
Firstly, please sanitise your user input before using it directly in a query!!! - also read this.
Secondly - the problem is that your calls to mysql_query() should be inside the if statements. With what you have done, mysql_query() is executed regardless, only the SQL statement itself is changed by the if. This means that if the first if condition is true, but all the others are false, the first statement will be executed 4 times.
Change your code to:
if (isset($_POST['distance'])) {
$dist = mysql_real_escape_string($_POST['distance']);
$sql = "INSERT INTO sportevent_parameters.Distance(value, user_ref, event) VALUES ('$dist', '$id', '$event')";
mysql_query($sql, $con)
or die("MySQL Error: ".mysql_error());
}
// etc etc
Edit: The mysql_query's should be inside the if statements so it does not get called if the if is not called. I would also check the variables you are passing.
Multiple SQL statements in one query are not supported in PHP. You have to split up each SQL statement into separate queries to the database.
Link to PHP Manual: http://php.net/manual/en/function.mysql-query.php

Categories