Some code starts with selecting data then check if row numbers are 0 to insert then continue the normal process. The problem is that the normal process is depending on the select statement which does not exist because it was stored before the insert. How can I refresh data request inside PHP without ajax or anything related to html? Here's an example to explain:
$user = $_GET['user']; // not stored user
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
$rownum = mysql_num_rows($select);
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
/* Here comes the problem */
if($row['something'] == 0){
die("Not found !"); // THIS if returns true since it was not found at first place before inserting
// i want it to refresh the $select data so it could be read as 1
}
How I solved it so far is by repeatedly using the $select and $row code below the insert statement
if(!$rownum){
mysql_query("INSERT INTO table (username, something) VALUES ('$user', 1)");
}
$select = mysql_query("SELECT * FROM `table` WHERE username = ".$user);
$row = mysql_fetch_array($select);
[..]
I want a simpler way to do this
If you know whats in the newly created record, you could just create a new array $row=array('username'->'bob', ...);
BUT if you have default values in the table, or add other things later, you going to have to do a second select.
$user=urldecode($_GET['user']);
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($select);
}
else
{
mysql_query("INSERT INTO table (username, something) VALUES ('".mysql_real_escape_string($user)."', 1)");
$result=mysql_query("SELECT * FROM `table` WHERE username='".mysql_real_escape_string($user)."'");
if(!$result) die("SQL ERROR");
if(mysql_num_rows($result)==0) die("MAJOR ERRORS IN SQL");
$row = mysql_fetch_array($result);
}
I prefer to use $result as this is the result of you running the query.
Related
I need to insert values into multiple table. Please correct my code because it just double the inserted value on table_attendace
if(isset($_POST['text']))
{
$text =$_POST['text'];
// insert query
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW())";
$query =mysqli_query($conn,$sql) or die(mysqli_error($conn));
if($query==1)
{
$ins="INSERT INTO table_attendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn));
if ($quey==1) {
$_SESSION['success'] = 'Action Done';
}else{
$_SESSION['error'] = $conn->error;
}
}
}
In the second query, you reused the first query $sql again, instead of using $ins.
It should be
$quey=mysqli_query($conn,$ins) or die(mysqli_error($conn));
you can write two queries in single variable with semicolon then you can save the same data in both table.
And
$quey=mysqli_query($conn,$sql) or die(mysqli_error($conn)); -> in this line you placed the $ins variable wrongly instead of $ins.
$sql = "INSERT INTO table_attendance(NAME,TIMEIN) VALUES('$text',NOW()); INSERT INTO table_ttendancebackup(NAME,TIMEIN) VALUES('$text',NOW())";
$query = mysqli_query($conn, $sql) or die(mysqli_error($conn));
How do i get details from a table to another table when a user is logged in. The details include their names (first, last), email and uid. The table that I want to fetch data is from the data entered when the user was registering. So does my code make any sense or is there any other way to achieve what I'm asking for? I have also attached pictures.
My purpose for this is to know which user entered the amount (bidamount)
Data comes from:
Data goes to:
<?php
if (isset($_POST['button'])) {
$bidamount = $_POST['bidamount'];
$ratings = $_POST['ratings'];
//TO ALERT SUBMISSION OF BLANK FIELDS(IT DOESN'T PREVENT SUBMISSION OF BLANK FIELD THOUGH)
if (!$bidamount) {
echo "can't submit blank fields";
}
//TO CONFIRM YOU ARE CONNECTED TO YOUR DATABASE (OPTIONAL)
$connection = mysqli_connect('localhost', 'root', '', 'tickmill_auctions');
if ($connection) {
echo "we are connected";
} else {
die("connection failed");
}
// TO INSERT USER DETAILS IN THE TABLE
if (isset($_SESSION['u_uid'])) {
$uid = $_SESSION['u_uid'];
$query = "SELECT * FROM tickmill_auctions WHERE user = '$uid'";
$result = mysqli_query($conn, $sql);
$resultcheck = mysqli_num_rows($result);
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$insert = mysql_query("INSERT INTO `son_of_man`
(`first`,
`last`,
`uid`,
`email`)
SELECT `first`,
`last`,
`uid`,
`email`
FROM `tickmill_auctions`
WHERE `user` = '$uid'");
}
}
//TO INSERT username and password from field to jossyusers database
$query = "INSERT INTO son_of_man(bidamount, ratings) VALUES('$bidamount','$ratings')";
$result = mysqli_query($connection, $query);
if (!$result) {
die("OOPPS! query failed" . mysqli_error($connection));
}
}
?>
You no need to add the full user detail in another table, read Normalization in SQL, just used the id of the user as foreign id to store the data in bid table. And then when you show the result on front view, you can use the JOINS to get the data from 2 tables.
And morevoer in query SELECT * FROM tickmill_auctions WHERE user = '$uid', there is no user field in any table.
I am attempting to post a column into my database here as a test and I am unable to do so. I've used the code below and it doesn't seem to be posting. Unless I am missing a trick with PHPmyAdmin I cannot seem to get it working. Any chance anyone could help? Thanks in advance!
<?php
$link = mysqli_connect("XXXX", "XXXX",
"XXXX", "XXXX");
if (mysqli_connect_error ()) {
die("The connection has failed");
}
$query = "INSERT INTO `users` (`email`, `password`)
VALUES('owen#owen.com', 'hfudhf8ahdfufh')";
mysqli_query($link, $query);
$query = "SELECT * FROM users";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo"Your Email is ".$row["email"];
echo" and your Password is ".$row["password"];
}
?>
The problem is that you're only fetching one row of results. Unless the table was empty before you ran the script, there's no reason to expect that row to be the one that you just added.
If the table has an auto-increment ID field, you can fetch that row:
$query = "SELECT * FROM users WHERE id = LAST_INSERT_ID()";
I have this code to select all the fields from the 'jobseeker' table and with it it's supposed to update the 'user' table by setting the userType to 'admin' where the userID = $userID (this userID is of a user in my database). The statement is then supposed to INSERT these values form the 'jobseeker' table into the 'admin' table and then delete that user from the 'jobseeker table. The sql tables are fine and my statements are changing the userType to admin and taking the user from the 'jobseeker' table...however, when I go into the database (via phpmyadmin) the admin has been added by none of the details have. Please can anyone shed any light onto this to why the $userData is not passing the user's details from 'jobseeker' table and inserting them into 'admin' table?
Here is the code:
<?php
include ('../database_conn.php');
$userID = $_GET['userID'];
$query = "SELECT * FROM jobseeker WHERE userID = '$userID'";
$result = mysql_query($query);
$userData = mysql_fetch_array ($result, MYSQL_ASSOC);
$forename = $userData ['forename'];
$surname = $userData ['surname'];
$salt = $userData ['salt'];
$password = $userData ['password'];
$profilePicture = $userData ['profilePicture'];
$sQuery = "UPDATE user SET userType = 'admin' WHERE userID = '$userID'";
$rQuery = "INSERT INTO admin (userID, forename, surname, salt, password, profilePicture) VALUES ('$userID', '$forename', '$surname', '$salt', '$password', '$profilePicture')";
$pQuery = "DELETE FROM jobseeker WHERE userID = '$userID'";
mysql_query($sQuery) or die (mysql_error());
$queryresult = mysql_query($sQuery) or die(mysql_error());
mysql_query($rQuery) or die (mysql_error());
$queryresult = mysql_query($rQuery) or die(mysql_error());
mysql_query($pQuery) or die (mysql_error());
$queryresult = mysql_query($pQuery) or die(mysql_error());
mysql_close($conn);
header ('location: http://www.numyspace.co.uk/~unn_v002018/webCaseProject/index.php');
?>
Firstly, never use SELECT * in some code: it will bite you (or whoever has to maintain this application) if the table structure changes (never say never).
You could consider using an INSERT that takes its values from a SELECT directly:
"INSERT INTO admin(userID, forename, ..., `password`, ...)
SELECT userID, forename, ..., `password`, ...
FROM jobseeker WHERE userID = ..."
You don't have to go via PHP to do this.
(Apologies for using an example above that relied on mysql_real_escape_string in an earlier version of this answer. Using mysql_real_escape_string is not a good idea, although it's probably marginally better than putting the parameter directly into the query string.)
I'm not sure which MySQL engine you're using, but your should consider doing those statements within a single transaction too (you would need InnoDB instead of MyISAM).
In addition, I would suggest using mysqli and prepared statements to be able to bind parameters: this is a much cleaner way not to have to escape the input values (so as to avoid SQL injection attacks).
EDIT 2:
(You might want to turn off the magic quotes if they're on.)
$userID = $_GET['userID'];
// Put the right connection parameters
$mysqli = new mysqli("localhost", "user", "password", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Use InnoDB for your MySQL DB for this, not MyISAM.
$mysqli->autocommit(FALSE);
$query = "INSERT INTO admin(`userID`, `forename`, `surname`, `salt`, `password`, `profilePicture`)"
." SELECT `userID`, `forename`, `surname`, `salt`, `password`, `profilePicture` "
." FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "UPDATE user SET userType = 'admin' WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$query = "DELETE FROM jobseeker WHERE userID=?";
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('i', (int) $userID);
$stmt->execute();
$stmt->close();
} else {
die($mysqli->error);
}
$mysqli->commit();
$mysqli->close();
EDIT 3: I hadn't realised your userID was an int (but that's probably what it is since you've said it's auto-incremented in a comment): cast it to an int and/or don't use it as a string (i.e. with quotes) in WHERE userID = '$userID' (but again, don't ever insert your variable directly in a query, whether read from the DB or a request parameter).
There's nothing obviously wrong with your code (apart from it being insecure with using non-escaped values directly from $_GET).
I'd suggest you try the following in order to debug:
var_dump $userData to check that the values are as you expect
var_dump $rQuery and copy and paste it into phpMyAdmin to see if your query is not as you expect
If you don't find your problem then please post back your findings along with the structure of the tables you're dealing with
i have a field in table opt named confirm of type tinyint. i want to insert value(1) by this statement but it is not working can any one help??
$connect= mysql_connect("localhost","root") or die ("Sorry, Can not connect to database");
mysql_select_db("login") or die (mysql_error());
$user=$_POST['staff'];
echo $user;
$query="SELECT * from users where username='$user' ";
$result=mysql_query($query,$connect) or die(mysql_error());
$row=mysql_fetch_array($result);
$uid=$row['userid'];
echo $uid;
$query="SELECT * from opt where userid='$uid' ";
$result=mysql_query($query,$connect) or die(mysql_error());
$row=mysql_fetch_array($result);
if($row['confirm']==0)
{
$query = "INSERT INTO opt (confirm) values(1)";
echo 'The user selected options has confirmed';
}
?>
You are not executing the query.
add an extra
$result=mysql_query($query,$connect) or die(mysql_error());
after the line
$query = "INSERT INTO opt (confirm) values(1)";
Apart from not executing the "InSERT STATEMENT",
You should probably be using an
"UPDATE OPT SET CONFIRM = '1' WHERE USERID = $user;"
as the row already exists ('cause you managed to select it!).
$query is a variable and there's no reason that it would cause a record to magically get inserted into the opt table.
You need to insert the following line after $query = "...":
mysql_query($query);
Also, I hopethat's not the code you're running in production.
You need to have the following somewhere:
$user = mysql_real_escape_string($user);
Why is not working? what error is throwing?
Check the other fields of the table...