I have two tables named 'Students_tbl' and 'admission'. I want to insert admission number in both tables at the same time such that in the 'students_tbl', it is a foreign key while in the 'admission' table, it is a primary key. The 'students_tbl' has a primary key of "std_index"
I am using one html form.
The codes I have written are outputting an error. Thanks for your replies in advance
Here are the codes
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
// Check connection
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr];
$sql = "INSERT INTO students_tbl (std_index,std_national_number)
VALUES ('$identification','$National_Number')";
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}ELSE {
die ('Thank you for registering');
}
}
?>
You are missing a closing bracket and quote
You're not executing the first query before overwriting $sql
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr']);
$sql = "INSERT INTO students_tbl (std_index,std_national_number) VALUES ('$identification','$National_Number')";
mysqli_query($manzu,$sql);
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}else {
die ('Thank you for registering');
}
}
?>
Related
I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"
I have created an application that takes information from the form and puts the details into a database table called "queue". The tables consists of entities "Position" (Primary Key, Autoincrement), "Name", "Service" and "QueuedAt".
I get this SQLlite::exec error while running my application.
Warning: SQLite3::exec(): near "jghjhgfjhgf": syntax error in E:\Programy\xampp\htdocs\QueueAppLocal\process.php on line 31
near "jghjhgfjhgf": syntax error
This is my process.php file that tries to insert form details into the table
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('queue.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
if(isset($_POST['formSubmit'])) {
$varFirstName = $_POST['formFirstName'];
$varLastName = $_POST['formLastName'];
$varTitle = $_POST['formTitle'];
$varService = $_POST['formServices'];
$varFullName = $varTitle . " " . $varFirstName . " " . $varLastName;
}
$sql =<<<EOF
INSERT INTO queue (Name,Service,QueuedAt)
VALUES ($varFullName, $varService, CURRENT_TIME);
EOF;
$ret = $db->exec($sql);
if(!$ret){
echo $db->lastErrorMsg();
} else {
echo "Records created successfully\n";
}
$db->close();
Just realised what the problem is. In $sql values I forgot to put the variable in single quotes like so VALUES ('$varFullName', '$varService', CURRENT_TIME);
I created a form using php, mysql and xampp server. The problem is that whatever I write in this form it shows that the "message failed to send" and even when I check my db using http://localhost/phpmyadmin/ the message is not there. Here is the code.
P.S I followed a video tutorial and it is exactly the same that made me totally lost. Please help.
The Connection code is:
<?php
$db_host = 'localhost';
$db_user= 'root';
$db_pass= 'the password';
$db_name= 'chat';
if ($connection= mysql_connect($db_host, $db_user, $db_pass)) {
echo "Connected to Database Server...<br />";
if ($database= mysql_select_db($db_name, $connection)) {
echo "Database has been selected... <br />";
} else {
echo "Database was not found. <br />";
}
} else {
echo "Unable to connect to MYSQL server.<br />";
}
?>
And the function code is:
<?php
function get_msg() {
$query = "SELECT 'Sender', 'Message' FROM 'chat' . 'chat'";
$run = mysql_query($query);
$messages= array();
while($message = mysql_fetch_assoc($run)) {
$messages[]= array ('sender' =>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
if($run = mysql_query($query)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
I have found the problem in your SQL query:
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
You have to specify the fields there, the SQL query is invalid. Also you have used the wrong escape characters. This works:
$query = "INSERT INTO `chat`.`chat` (`ID`, `sender`, `message`) VALUES (null, '{$sender}', '$message')";
You do not have to specify a null value if you use AUTO_INCREMENT:
$query = "INSERT INTO `chat`.`chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
And please use MySQLi instead of MySQL because it is deprecated. Furthermore, the database should not be specified twice, simple use:
$query = "INSERT INTO `chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
$query = "INSERT INTO `chat`.`chat` VALUES (null, '{$sender}', '$message')";
Note the ` and it's not '
I am a novice in PHP and MySQL so I tend to always explicitly exit or die on MySQL on errors.
<?php
$db = new mysqli('host', 'username', 'password', 'db');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
// no reason to continue, no db connection
}
$statement="SELECT * from `bufferlines` WHERE `beloeb` >'-400' AND `tekst` LIKE 'Dankort-nota SuperB%'";
if(!$res=$db->query($statement)){
printf("Error: %s\n", $db->error); //show MySQL error
echo "<br />".$statement; // show the statement that caused that error
exit("Error 4");//no reason to continue, show where in code
}
?>
This way I get it thrown in my face and cannot get any further until I have pinned down and corrected the error.
The number in exit("Error 4") is only to find the place in the code where it went wrong and thus is unique.
I know this is counter productive when you know your stuff, but for me it's an invaluable learning tool together with php.net dev.mysql.com and stackoverflow.com
Trying to create a simple cumulative addition script in PHP (or JS):
1) enter any integer(4 digits or less), click submit, number entered is displayed and saved on the same web page
2) enter another number, click submit, number entered is added to previous number and total is saved and displayed on the web page
Repeat …….
Example: the mantra counter at garchen.net
Below is the code I have so far
In Index.php:
<form method="post" action= "process-mantra-form-ami.php" >
<p><strong>Amitabha Million Mantra Accumulation: </strong><br></p>
<div style="margin-left: 20px;">
<p>OM AMI DEWA HRI</p>
<input type="text" name="accumulation" size="10" maxlength="6">
<input type="submit" value="Submit Your Mantra" name="B1"><br>
<span id="mani">Amitabha Mantra Count: <?php echo $newValue; ?> </span>
<p></p>
</div>
</form>
I am getting confused about the form processing php. Im attempting to use my local mamp server for the db. Do I create a connection, create a database, and a table, insert form data into table, and retrieve data back to index.php all at the same time in the process-mantra-form-ami.php file?
You guys made it seem easy in my last post, but there seems to be a lot to it. I know my code below is incomplete and not quite correct. Help!
PROCESS-MANTRA-FORM-AMI.PHP code below
<?php
// Create connection
$con=mysqli_connect("localhost:8888","root","root","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$accumulation = mysqli_real_escape_string($con, $_POST['accumulation']);
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql)) {
echo "Database my_db created successfully";
} else {
echo "Error creating database: " . mysqli_error($con);
}
// Create table "Mantras" with one column 'Num'
$sql="CREATE TABLE Mantras (Num INT)";
if (mysqli_query($con,$sql)) {
echo "Table mantras created successfully";
} else {
echo "Error creating table: " . mysqli_error($con);
}
// Insert form data into table
$sql="INSERT INTO Mantras (Num INT)
VALUES ('$num')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
// update database
mysqli_query($con,"UPDATE Mantra SET Num = num + 1");
}
mysqli_close($con);
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
try this out... (sorry, bored tonight)
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
$conn->query($sql)
$conn->prepare($sql)
$conn->error
http://php.net/manual/en/class.mysqli-stmt.php
$stmt->bind_param('ss',$val1,$val2)
$stmt->bind_result($res1,$res2)
http://php.net/manual/en/mysqli.construct.php
<?php
$host = 'localhost'; // localhost:8888
$user = 'root';
$pass = ''; // root
$dbnm = 'test';
$conn = mysqli_connect($host,$user,$pass,$dbnm)
or die('Error ' . $conn->connect_error);
// for testing.... so i can run the code over and over again and not
// get errors about things existing and stuff
run_statement($conn,"drop database if exists `my_db`;",'cleared old db');
run_statement($conn,"drop table if exists `mantras`;",'cleared old table');
run_statement($conn,"drop table if exists `two_col_table`;",'cleared old table');
// Create database
$sql = 'create database my_db';
$err = run_statement($conn,$sql,'Database creation');
if (!$err) $conn->select_db('my_db');
// Create table "Mantras" with one column 'Num'
$sql = 'create table mantras (num int)';
$err = run_statement($conn,$sql,'Table mantras');
if (!$err) {
$sql = 'insert into mantras (num) values ( ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('d',$num); // d is for digit but s (string) would work too
$num = 1;
$stmt->execute();
$num = 2;
$stmt->execute();
$stmt->close();
echo ($conn->error) ? "insert errored: {$conn->error}" : 'insert ran succesfully';
// update database
$sql = 'update mantras set num = num + 1';
run_statement($conn,$sql,'Update database');
}
// Create table "test" with two columns
$sql = 'create table two_col_tbl (num int, txt varchar(10))';
$err = run_statement($conn,$sql,'Table two_col_tbl');
if (!$err) {
// demonstrating how to bind multiple values
$sql = 'insert into two_col_tbl values ( ?, ? )';
$stmt = $conn->prepare($sql);
$stmt->bind_param('ds',$num,$txt);
$num = 1; $txt = 'hello';
$stmt->execute();
$num = 2; $txt = 'world';
$stmt->execute();
$stmt->close();
// select statement
$sql = 'select num, txt from two_col_tbl';
$stmt = $conn->prepare($sql);
$stmt->bind_result($db_num, $db_txt);
$stmt->execute();
print '<table><tr><th colspan=2>two_col_tbl</tr><tr><th>num</th><th>txt</th></tr>';
while ($stmt->fetch()) {
print "<tr><td>$db_num</td><td>$db_txt</td></tr>";
}
print '<table>';
$stmt->close();
}
$conn->close();
function run_statement($conn,$statement,$descr) {
if ($conn->query($statement))
echo "$descr ran successfully";
else echo "$descr failed: {$conn->error}";
return $conn->error;
}
?>
<div>
<h2>Thank you for your <?php echo $num; ?> Amitabha Mantras!</h2>
<p>Remember to dedicate your merit.</p>
<p>Return to the main site</p>
</div>
Hey guys am working on a project for my college and there is one last part where i am stuck. It is about the user entering data into database and has a concatenation part where am stuck. The user has to insert a prize id and based on the prize name he enters there is a concatenation part which i will explain in the last.
this is my file where the insertion takes place:
$con=mysqli_connect("localhost","xxx","yyy","zzz");
if ($_POST['pid'] == ''||$_POST['pname'] == ''||$_POST['pamt'] == '')
{
header("location:adawdins_err.php");
}
else
{
$class = $_POST['class'];
$dept = $_POST['dept'];
$did = $_POST['did'];
$dcode = $_POST['dcode'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="INSERT INTO prizemaster (`prizeid`, `name`, `class`, `department`, `amount`, `donorid`, `deptcode`) VALUES ('$_POST[pid]', '$_POST[pname]', '$_POST[class]', '$_POST[dept]', '$_POST[pamt]', '$_POST[did]', '$_POST[dcode]')";
if (!mysqli_query($con,$sql1))
{
die('Error: ' . mysqli_error($con));
}
else
{
header("location:adawdins_suc.php");
}
}
mysqli_close($con);
and i want the output like this:
say if the user enters "best project" in prize name then i want it like
if(pname=="Best Project")
{
pidtemp="ABC"+$pid;
}
and after this i will use pidtemp to insert in the database file!
if(pname=="Best Project")
{
pidtemp="ABC"+$pid;
}
replace above code with below
if($pname=="Best Project")
{
$pidtemp="ABC".$pid;
}