Can't insert data into mutiple mysql tables - php

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.

Related

how can I insert data into table php/mysql? [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 3 years ago.
I'm making a quiz and once the calculation of the grade is finished, I want to add that data to test_attempt table.
Here's its structure.
Here's the code of the query:
<?php
$connection = mysqli_connect("localhost", "root", "", "vartvald");
if ($connection->connect_error) {
die("Connection failed:" . $connection->connect_error);
}
$user=$_SESSION['user'];
$userid=$_SESSION['userid'];
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
('',null,'$grade','$top_grade','$userid','$fk');";
var_dump($sql);
$connection->close();
?>
What am I doing wrong?
You have few mistakes. Your main problem is that you never prepared any query and never executed it. To do it you need to use prepare(), bind_param(), and execute(). Also you are not opening the mysqli connection correctly and your error checking will never work (Please read: Should we ever check for mysqli_connect() errors manually?)
After fixing your errors your code would look something like this:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli("localhost", "root", "", "vartvald");
$connection->set_charset('utf8mb4');
$user = $_SESSION['user'];
$userid = $_SESSION['userid'];
$stmt = $connection->prepare('INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES(NULL,NULL,?,?,?,?)');
$stmt->bind_param('ssss', $grade, $top_grade, $userid, $fk);
$stmt->execute();
I have not validated whether your SQL is correct in itself, but if you have error reporting switched on, PHP should tell you if you have a mistake.
Your code will never add data in the database because you aren't calling any funciton that insert data:
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
('',null,'$grade','$top_grade','$userid','$fk');";
var_dump($sql);
// missed code to insert data in the database
$connection->close(); // here you close the connection
Before closing the connection, call mysqli_query:
mysqli_query($connection,"$sql");
Try this:
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
(CURRENT_TIMESTAMP,null,'$grade','$top_grade','$userid','$fk');";
Try the following, here you can see that the CURRENT_TIMESTAMP is passed as first params for data and also below the $sql you can see the mysqli_query which is useed here to execute the insert query.
$sql = "INSERT INTO test_attempts (date, id, mark, top_mark, fk_user, fk_test) VALUES
(CURRENT_TIMESTAMP,null,'$grade','$top_grade','$userid','$fk');";
mysqli_query($connection, $sql);

Having hard time querying database

I'm trying to insert data in mysql using php I have FK with parishionerID
my query is correct but I always get the Error querying database. It doesn't show me
the specific query that I'm having an error with. BapID is PK. Hope you can help me resolve this. Thanks.
$con = mysqli_connect('localhost', 'root', '', 'RMS') or die('Error connecting to MySQL server');
$sql="INSERT INTO baptismal (ParishionerID, BapID, Datebaptism, Ministerbaptism, Sponsor, Sponsor2, Volume, Page)
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
$result = mysqli_query($con, $sql) or die('Error querying database.');
mysqli_close($con);
If I input datas in mysql manually this is the query which is pretty have the same with my query.
INSERT INTO `rms`.`baptismal` (`ParishionerID`, `BapID`, `Datebaptism`, `Ministerbaptism`, `Sponsor`, `Sponsor2`, `Volume`, `Page`) VALUES ('80', NULL, '2014-07-16', '131', 'sdasd', '123123', '123123', '123');
There seems to be only Syntax error. Youre missing '
VALUES('$id', NULL, '$Datebap', '$Ministerbap', '$Sponsor', '$Sponsor2, '$Volume', '$Page')";
----------------------------------------------------------------------^
Your $Sponsor2 is not properly quoted.
FYI: Let the script print out the error SQL too.
Convert your line as:
$result = mysqli_query($con, $sql) or die('Error querying database: '.$sql);
Then, you will see the exact query that ran.
Do not print SQLs on the server mode.

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

add values to mysql database using php on ubuntu

n00b learning php from a book.
I'm trying to add data to a database called adv_php. I'm using the following snippet of code in the page that's receiving the data from the post:
<?php
$dbc = mysqli_connect('host', 'name', 'password', 'adv_php');
if (mysqli_connect_errno())
{
echo "Failed to connec to MySQL" . mysqli_connect_error();
}
$parent_id = $_POST['parent_id'];
$task = $_POST['task'];
// Add the task to the database.
$q = "INSERT INTO (parent_id, task) tasks VALUES ($parent_id,'$task')";
mysqli_query($dbc, $q);
?>
I know this code connects to the database elsewhere as I can retrieve info from the database. With this page, I don't get an error, I just get a blank page, and nothing is added to the database Where am I going wrong?
Your query is wrong...Change it ...
$q = "INSERT INTO tasks(parent_id, task) VALUES ($parent_id,'$task')";
you misplaced table_name, use below query
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";
Your insert statement is wrong
Try this
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";

What do you put in the parentheses of mysql_insert_id()?

I tried setting a variable like this: $test_id = mysql_insert_id($dbc); because I wanted to get the id of the last row inserted. I am able to connect to the database and insert the row but the next line (setting $test_id) it says this: supplied argument is not a valid MySQL-Link resource . Any ideas?
Here's the code:
$user_id = $_SESSION['user_id'];
$q = "INSERT INTO tests (user_id, title, subject, creation_date) VALUES ('$user_id', '$title', '$subj', NOW())"; //query to insert test details into tests table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$test_id = mysql_insert_id($dbc);
if (mysqli_affected_rows($dbc) == 1) {//if the query ran correctly and the test details were added to the database
$q = "INSERT INTO content (test_id, field1) VALUES ($test_id, '$content')"; //query to insert test content into content table
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
$dbc is defined like this:
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASS, DB_NAME);
From the comments:
Oh, I see now. You're mixing mysql_* with mysqli_* functions. Those are different libraries. They don't mix. Use mysqli_insert_id() instead.
You should put the link identifier (the output of mysql_connect(), not mysql_query())
mysql_insert_id implicitly calls SELECT LAST_INSERT_ID() which is session-specific.
Normally you can leave out that parameter; it will know that you have a database connection open. If you want to specify the connection, use the return value from mysql_connect:
$dbc = mysql_connect('localhost', 'mysql_user', 'mysql_password');
// later
echo mysql_insert_id($dbc);
Again, this is normally not necessary.
Also keep in mind that mysql_insert_id will only work after you've made an INSERT query where an index column with AUTO_INCREMENT was incremented. It will not return the latest ID that was inserted at some other time before the current session. For that you you could for example do:
SELECT MAX(id) FROM some_table;
The problem is that you're using a MySQLi resource in a MySQL function (note the missing i). There are 2 different extensions there. If you're using mysqli, don't switch to mysql. So just change that function to mysqli_insert_id($dbc);

Categories