I am using mysql_insert_id() on the first page (test2.php) to insert the same id on other tables that is submitted from different forms. The id is inserted perfectly however, when i want to insert the data from other forms (e.g: test.php), the data cannot be updated, I have to inform before this i was using insert and it is not systematic because it will insert a new data with new id. As reference, below are my php codings for page test2.php and test.php:
test2.php:
<?php
session_start();
include("auth.php");
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('tempahperalatan');
if(isset($_POST['submit'])){
$noID = $_POST['noID'];
$pemohon = $_POST['pemohon'];
$trkhMula = $_POST['trkhMula'];
$trkhAkhir = $_POST['trkhAkhir'];
$n_program = $_POST['n_program'];
$lokasi = $_POST['lokasi'];
$n_anjuran = $_POST['n_anjuran'];
$catatan = $_POST['catatan'];
mysql_query("INSERT INTO daftartempah (noID, pemohon, trkhMula, trkhAkhir, n_program, lokasi, n_anjuran, catatan) values ('$noID','$pemohon','$trkhMula','$trkhAkhir','$n_program','$lokasi','$n_anjuran','$catatan')");
mysql_query("INSERT INTO pasystems (noID) values ('$noID')");
mysql_query("INSERT INTO ict_1 (noID) values ('$noID')");
mysql_query("INSERT INTO pejabat (noID) values ('$noID')");
printf("Last inserted record has id %d\n", mysql_insert_id());
}
?>
For page test.php, there is an echo of variables is because I was testing whether it reads the variables, and surprisingly it reads because it appear at the top of the page of the data that I entered however, the noID does not appear and that means it does not fetch the same id from the previous page (test2.php) and I think that is the problem why my data was not updated. Can anyone help me about this problem because I'm a student studying web programming and some guidance would be so helpful, thank you in advance.
test.php:
<?php
session_start();
include("auth.php");
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('tempahperalatan');
if(isset($_POST['submit'])){
$noID = $_POST['noID'];
$microphones = $_POST['microphones'];
$amplifiers = $_POST['amplifiers'];
$loudspeakers = $_POST['loudspeakers'];
$mixers = $_POST['mixers'];
$catatan = $_POST['catatan'];
?>
<p><?php echo $microphones;echo $amplifiers; echo $loudspeakers; echo $mixers; echo $catatan; echo $noID; ?></p>
<?php
mysql_query ("UPDATE pasystems SET microphones='$microphones', amplifiers='$amplifiers', loudspeakers='$loudspeakers', catatan='$catatan' WHERE noID = '$noID'");
}
Please ask if my question is not clear for you to help me, I will try to help you understand my problem/question.
Related
I have a table for "threads" and a table for "comments" on my database. Both tables have an auto increment ID column, timestamp etc. There is also a "THREAD ID" column where I'd like to INSERT thread's IDs in the "comments" table.
My question is: how can I retrieve the auto increment ID number of the related thread's row from "threads" table and INSERT this number to the "comments" table's "THREAD ID" column every time when I insert a comment. So I can create a link between "comments" and "threads".
I'm somewhat beginner at PHP and I'd like to learn with the explanation of the code. Like which string is for what, which method is for what..
<?php
/*show error codes*/
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
/* database info*/
define('DB_NAME', 'imageboard');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '.mysqli_error());
}
$db_selected = mysqli_select_db($link1, DB_NAME);
if (!$db_selected) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME) VALUES ('$deger', '$deger2', '$deger3')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
?>
<?php
if(isset($_FILES['replyUserFile'])) {
$uploadName1 = $_FILES['replyUserFile']['name'];
$uploadTmp1 = $_FILES['replyUserFile']['tmp_name'];
$uploadType1 = $_FILES['replyUserFile']['type'];
// CORRECTION
$uploadName1 = preg_replace("#[^a-z0-9.,]#i", "_", $uploadName1);
// FILES TO directory
if(!$uploadTmp1) {
die("can't send...");
} else {
move_uploaded_file($uploadTmp1, "./images/$uploadName1");
}
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '. mysqli_error());
}
$db_selected1 = mysqli_select_db($link1, DB_NAME);
if (!$db_selected1) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//INSERT INTO tables
$sql1 = "INSERT INTO images (USERIMAGENAME) VALUES ('$uploadName1')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
// CHANGE THE NAME OF THE IMAGE FILE IN THE DIRECTORY TO DATABASE ID NUMBER
$last_id = mysqli_insert_id($link1);
$ext1 = pathinfo("./images/$uploadName1", PATHINFO_EXTENSION);
rename("./images/$uploadName1", "./images/$last_id".".".$ext1);
// GO BACK TO THREAD
header('Location: ./thread.php');
}
}
mysqli_close($link1);
?>
I'm wondering why others suggest you to use mysqli_insert_id() when you want to get the thread_id. As I know, mysqli_insert_id() will return you the successfully inserted id of the last mysql query.
But here, when I check your code, you are not creating the thread here. It's something that has been already created (earlier).
What you trying to accomplish is (As I understand), you want to store the 'thread_id' in your 'comment' table as a reference to which thread this comment was posted, right?
My suggestion is to use a hidden field in your comment form and pass the thread_id to the submit page.
Then you can retrieve 'thread_id' too, in the same way you get the replyNickname, replyComment etc.
And then, use that 'thread_id' inside your query.
Ex:
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
$thread_id = $_POST ['thread_id']; // Note this line
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME, THREAD_ID) VALUES ('$deger', '$deger2', '$deger3', '$thread_id')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
I hope what I understood is right. This is just a rough idea, you can pass the thread_id in anyway you want. But I don't see any point of using mysqli_insert_id() here.
//If the previous request triggered an auto increment
if (mysqli_insert_id($link)<>'') {
//retrieves the last ID
$lastID = mysqli_insert_id($link);
//do something
}
else {
//do something else...
}
Be sure that you chose INNODB engine in order to be able to handle foreign keys
Assuming you're using MySQL:
PDO (where $pdoConn is your PDO connection):
$yourlastID = $pdoConn->lastInsertId();
mysqli:
$yourlastID = $mysqli->insert_id;
If you are using MSSQL, use SCOPE_IDENTITY(). Read http://www.codeproject.com/Articles/103610/Difference-between-IDENTITY-SCOPE-IDENTITY-IDENT-C
create PROCEDURE [dbo].[spInsertIntoThreads]
(
#THREAD_ID int OUTPUT,
#Column1 varchar(50) = NULL,
)
AS
BEGIN
SET NOCOUNT ON;
Insert Into Threads(Column1)
values(#Column1);
SET #THREAD_ID=SCOPE_IDENTITY();
END
Hope it helps. :)
I have a little problem with my PHP code and database. Every time i refresh the page, a new empty row is being added to the database also when i open the page, what is the problem?
<?php
if (isset($_POST)) {
$con = mysql_connect("localhost","dwarfmaster","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_dwarfmaster", $con);
$name = $_POST['name'];
$release_year = $_POST['release_year'];
$publisher = $_POST['publisher'];
$genre = $_POST['genre'];
$sql = "INSERT INTO gamelist (name, release_year, publisher, genre)
VALUES
('$_POST[name]','$_POST[release_year]',
'$_POST[publisher]','$_POST[genre]')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
to check if the request method is post, use:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
if(isset($_POST)) will always return true
or simply change
if (isset($_POST))
to
if (isset($_POST['name']))
you can add the following code-:
if( !empty(array_filter($_POST)) ) { . . Code to insert data into data base
from form . . }
if (isset($_POST))
will always return true !
try
if (isset($_POST['name'])&&isset($_POST['release_year'])
&&isset($_POST['publisher'])&&isset($_POST['genre']))
instead to check each time for each and every variable !
Page 1 abc.html.. on submit it will jump to this PHP page .
This is page PHP1.php here i am trying to validate user input if name and id in in data he will be forwarded to fill out second part of registration if not it will just give error.
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = mysql_connect("localhost", "user", "password");
if (!$con)
{die('Could not connect: ' . mysql_error());}
mysql_select_db("mydbName");
if(isset($_POST['team_name'],$_POST['id'])){
$team_name = mysql_real_escape_string($_POST['team_name']);
$id = mysql_real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result= mysql_query("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$team_result = mysql_fetch_row($result);
if ($team_result[0] == '0') { //if does not exist print failed.
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}} } ?>
RegisterPART2.php is where i am checking my session exist or not (the one i started in last file). if not i want to redirect back to form one and fill that first then come to registration part 2
`<?php
session_start();
$name = $_SESSION['team']; //a value stored in session which i used on this page
if (($_SESSION["abc"] !== 'good')) {
header('Location: http://www.abc.com/page1.html'); //take back to stage 1 coz user did not fill first part.
}
else{
echo $name. 'you have completed register process part one you may continue!';
}
?>
If you're using the new MySQL version (MySQLi), so the first page will become:
<?php
session_start();
$_SESSION["acb"] = "good";
$_SESSION['team'] = $_POST['team_name'];
$con = new mysqli("localhost", "user", "password", "mydbName");
if (!$con) {
die('Could not connect: ' . $con->error());
};
if (isset($_POST['team_name'],$_POST['id'])) {
$team_name = $con->real_escape_string($_POST['team_name']);
$id = $con->real_escape_string($_POST['id']);
if (!empty($team_name)) {
$result = $con->prepare("SELECT COUNT(`teamname`) FROM `table` WHERE `teamname`='$team_name' AND `id`='$id'");
$result->execute();
$result->bind_result($one,$two,$three,$etc);
$result->fetch();
if (empty($one) and empty($two) and empty($three) and empty(etc)) { // may be and/or (pick one)
echo 'Varification failed';
} else {
header('Location: http://www.abc.com/REGISTERpart2.php');
}
}
}
?>
You may use the following alternative to header.
prinf('<script>window.location = "URL HERE"</script>');
It should do the same thing as header does.
I'm trying to retrive my first name and last name for viewprofile.php but i'm getting resource ID#5 . I am CREATING session in Login page after successful authentication. And I am trying to use it here. I'm trying to use a session which has been created to fetch the data from the database.
<html>
<h1> My Profile</h1>
<?php
session_start();
require "config.php";
$con = mysql_connect("localhost", $db_user, $db_pass);
if(!$con)
{
die('cound not connect: '. mysql_error());
}
mysql_select_db($db_name, $con);
# include 'new.php';
echo $_SESSION['username'];
#$usname = $_SESSION['username'];
#echo 'local var: ', $usname;
$sql1 = "SELECT * FROM register WHERE uname='".$_SESSION['username']."'" ;
#echo $sql1 ;
$result= mysql_query($sql1)or die(mysql_error());
#echo "res: " . $result;
while($row = mysql_fetch_array($result))
{
echo $row['fname']." ".$row['lname'];
echo"</br>";
}
mysql_close($con);
?>
</html>
I'm getting resource ID#5. Searched numerous places no luck. Kindly help
Unless I'm mistaken mysql_fetch_array will give you values that can be expressed as $row[0], $row[1] etc whereas mysql_fetch_assoc is what you're trying to use to get $row['fname'] etc
Change your code to
while($row = mysql_fetch_assoc($result))
In either case a print_r($row) within your while loop will you how it's made up.
Ok, So I have a external php script that get data from a DB and displays it in a table. I want to run it in a specific div in my html so the data gets echoed out in the right place?
Any ideas how to do that?
Html div
<div id="statsContent">
<?php include('updatestats.php'); ?>
</div>
Heres the PHP code.
<?php
//Start session
session_start();
//Make sure user is logged in
require_once('auth.php');
//Include database connection details
require_once('config.php');
//Connect to DB
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Create Querys
$query = "SELECT * FROM stats WHERE member_id='" . $_SESSION['SESS_MEMBER_ID'] . "' ";
$result = mysql_query($query);
//Gather the whole row into an array
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$money = $row['money'];
$bank_money = $row['bank_money'];
$ap = $row['ap'];
$exp = $row['exp'];
}
//Now create a table to display the data to the user
echo "<table>
<tr>
<td>Money $$money</td>
<td>Action Points $ap</td>
<td>Experience $exp</td>
</tr>";
?>
you can include PHP script in any tag by calling
include("path_to/myscript.php") or require("path_to/myscript.php")
<div>
<?php include("path_to/myscript.php"); ?>
</div>
<div><?php *whatever you want to do inside the div*?></div>
just include it inside your div by using:
<?php include('filename.php'); ?>