See which table has affected another table SQL-Server - php

I have created a program in which a user will enter what device they are using and will then perform a task to test their performance based on the device they are using. The user will be taken to a start page in which they will type what device they are using, select from a drop down what hand they are using and the screen width and height will be collected via Javascript along with a primary key called DeviceID. So far all this data is stored in my first table. The second table contains data relating to the user performance such as time etc.
The first table has a one-to-many relationship with the second table as for every 1 device there will be approximately be 100 results.
The part which I am struggling with however is being able to recognise which device entered has gotten which results (i.e. DeviceID 1 got these results, DeviceID 2 got those results etc) and how I can view this relationship.
Edit:
First PHP Page
<?php
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$HandUsed = $_POST['HandUsed'];
if(isset($_POST['submit']))
{
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
$phoneType = $_POST['phoneName'];
$HandUsed = $_POST['HandUsed'];
echo 'hello';
$sql = "INSERT INTO deviceInfo (screenWidth, phoneType, screenHeight, HandUsed)
VALUES ('$screenWidth','$phoneType', '$screenHeight', '$HandUsed')";
if (sqlsrv_query($conn, $sql)) {
// echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
Second PHP Page
<?php
include 'db.php';
$Xpos = $_POST['Xpos'];
$Ypos = $_POST['Ypos'];
$StartID = $_POST['StartID'];
$Random = $_POST['RandomID'];
$Time = $_POST['timeTaken'];
$sql = "INSERT INTO UserResults6(Xpos, Ypos, StartID, RandomID, TimeTaken, DeviceID)
VALUES ('$Xpos', '$Ypos', '$StartID', '$Random', '$Time', SELECT DeviceID from deviceInfo)";
if (sqlsrv_query($conn, $sql)) {
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
?>
In the first page everything works as intended and I am given the information that I want along with an auto-incremented DeviceID. In the first page everything works up until the select statement to get the DeviceID. The outcome that I would be hoping for would be for the DeviceID to match with DeviceID from the prior table but I am currently unsure of how to go about achieving this.

Related

php script for selecting/inserting, only succeeds for one row

I made a fairly simple script to take records from a development database, and for each selected record insert it into production and get the newly created ID.
This "Works" but only for one record. WHen I run this script, it successfully connects, selects, inserts, and prints the newly inserted record's ID but then the script just stops and when I check the database only one new record is there, even though there are over 500 records in the source table
Is it just becuase I'm using While instead of foreach? I think I've done something similar before with a while loop but this isjust dying on me after one successful attempt.
if($DB2connDEV && $DB2connPROD){
$getDevelopment = "
SELECT * FROM TEST_TABLE; // there are over 500 records in here
";
$stmt = odbc_exec($DB2connDEV, $getDevelopment);
while($gettingDevelopment = odbc_fetch_array($stmt)){
$originalID = $gettingDevelopment['identity'];
$insertTable = "INSERT INTO testing_insert_php (name) VALUES ($originalID)";
$getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";
$stmt = odbc_exec($DB2connPROD, $insertTable);
$stmt = odbc_exec($DB2connPROD, $getIdentity);
$row = odbc_fetch_array($stmt);
$ret = $row['LASTID'];
if($ret) {
echo "Last Insert ID is : " . $ret . "\n";
} else {
echo "No Last insert ID.\n";
}
}
odbc_close($DB2connPROD);
}

How to check if the DB already have the data or insert new data

What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.

how to update a single column of db without deleting its previous data?

i am updating a single column with many values using comma between them. they are working fine. but if update same column from other user the value inserted by previous users deleted. i want to keep values of previous user also with the insertion of new user value. and i also dont want to repeat the same value again because values i m using are unique ids..
// update student list
$venue = ($_GET['venue']);
$district = ($_GET['dis']);
if(isset($_POST['submit']))
//print_r ($_POST);
{
#$std_list=implode(',',$_POST['std_list']);
if(empty($std_list))
{
$error = 1;
$get_value = "Please select you event students.";
}
else
{
//$query = mysql_query("INSERT INTO events (std_list)
//VALUES('".$std_list."')") or die(mysql_error());
$query = mysql_query("UPDATE events SET std_list='".$std_list."' WHERE
id='".$district."' ") or die(mysql_error());
//echo "$msg";
echo "Students list submitted successfully";
}
}
if any query you can ask again. values i am inserting are integers only. Same integer cant be used by two different users.
try this?
$query = mysql_query("UPDATE events SET std_list = CONCAT( std_list, '".$std_list."') WHERE
id='".$district."' ") or die(mysql_error());

add rows with loop max value +1

I'm trying to add rows to the database based on the input value.
i.e. If input as "5", query will insert 5 rows to database. (this part is working fine)
Now, I need the bed_number to be +1 to the existing max(bed_number) but i can't seems to get it to work.
If existing max(bed_number) returns 5, than the query should add "6,7,8,9,10, etc" as the bed_number for the 5 entries.
If existing max(bed_number) returns null, than it should add "1,2,3,4,5, etc"
Right now, the result always return 1,2,3,4,5... regardless of the max count.
What i have here now is:
global $conn;
if ($values["number_of_bed"])
{
$add1 = $values["number_of_bed"]+1;
$existingBed = "select Max(bed_number) from bed where bed =" '".$i."'" +1;
for ($i=1;$i<$add1;$i++)
{
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$existingBed."')";
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();
//echo "Number of customers: " . $data["c"];
global $conn;
if ($values["bed_number"])
{
$add1 = $values["bed_number"]+1;
//for ($i=1;$i<$values["bed_number"];$i++)
for ($i=1;$i<$add1;$i++)
{
$sql = "select max(bed_number) as c from bed where unit_id =" . $values["unit_id"];
$rs = CustomQuery($sql);
$data = db_fetch_array($rs);
$strInsert = "insert into bed (unit_id,bed_number) values ('".$values["unit_id"]."','".$data["c"]."'+1)";
// add more fields from the add page to be inserted into database
db_exec($strInsert,$conn);
}
header("Location: bed_list.php");
// Exit and Redirect to the list page after updating database
exit();
}

Select and then Insert Query (PHP with MYSQLI) Not working

Hello I've a table named as "register" in which i've some records Lets says (10)
I want to first count that records and then save it into another table named as "not" i.e. Notification(Handler Name)
Here's the code which i'm using but unfortunately its not working..
Here's my config.php
<?php
$con = new mysqli('localhost','root','','admin');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
and here's abc.php
<?php
include('config.php');
$sql2 = "INSERT INTO not VALUES((SELECT count(*) as count FROM register))";
$result2 = mysqli_query($con, $sql2);
if($result2->num_rows>0)
{
while($rw1=$result2->fetch_array())
{
$value1 = $rw1['count'];
echo $value1;
}
}
?>
not is reserved word. So you should use like this:
$sql2 = "INSERT INTO `not` VALUES((SELECT count(*) as count FROM register))";
Basically i'm working on a project similar to Facebook Notification System
I've a Registration Form through which users are registered and all entries will be saved in a database named as "admin" with table name as "register"
Clear or not ?
Suppose I've 10 Users and I want to first show No. 10 as Notification Number at top bar as a popup tooltip
Just follow this example which i'm using
[http://demos.9lessons.info/notifications_css/index.php][1]
After that I want to Perform this thing that when someone opens the notification bubble, that 10 Number Goes out and in backend, i'm thinking that to store that ROW COUNT into another table and after Jquery click function, that table value goes to ZERO and when any new user is registered, then it increments the counter with match the previous value..
Sounds or not ??
change your table name as suggested by #phpPhil
plus try this query
$sql2="INSERT INTO not SELECT count(*) as count FROM register";
UPDATED
made your connection in this file.
$con = new mysqli('localhost','root','','admin');
$sql = "SELECT count(*) as count FROM register";
this query will return only one or zero rows so dont use while
$result = $con->quer($sql) or die($con->error);
if($result->num_rows>0)
{
$rw=$result->fetch_array(MYSQLI_ASSOC);
$value = $rw['count'];
echo $value; here to check what you get here
//preiously you had check if value is not empty. which is wrong because it will never empty it will either 0 or any other value
if($value!=0)
{
$jh ="update noti set noti='$value'";
$res=$con->query($jh) or die($con->error);
}
else
{
$ab ="insert into noti(noti) values('$value')";
$res1=$con->query($ab) or die($con->error);
}
}

Categories