PHP How to edit database entry I just created? (basic) - php

In my site, I have a page to create an site page (addpage.php) and then send the user to a listing of all pages (pages.php), from which they can click on the page they'd like to edit (editpage.php).
I do this because my editpage.php uses the page_id variable to select the page's info from the database and I don't know how to select that variable without first going to pages.php to list all those variables.
I'd like to be able to complete addpage.php and then GO DIRECTLY to editpage.php - but how do I select the page_id that will only just be created on the insert into the database?
My code on addpage.php is basically
$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}

$q = "INSERT INTO pages (page_name, page_content) VALUES ('$name', '$content' )";
$r = mysqli_query ($dbc, $q);
$id=mysql_insert_id();
if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.
// send to pages.php
} else { // If it did not run OK.
echo '<p>The page has NOT been added</p>';
}
You can check php manual.

You have to do a query to your database, asking what've been the last inserted id. You can do this running this query:
SELECT LAST_INSERT_ID() as lastId
Then you get the value as you do with any regular query (because this is a regular query actually).
In php there's a function called mysql-insert-id which is more elgant.
Good luck!

If you're using mysql, you can get the ID of the last insert by running the following query SELECT LAST_INSERT_ID(). This will get you the ID.

Related

Insert statement after user registration with loop

I have registration form which works fine. Now I want to add second query after user is registered. This query should have loop and add exactly 10 new rows in another table. This is the query with loop
if ($conn->query($sql) === TRUE) {
$result = "Request successfully submitted.";
$new_id = $db_con->lastInsertId();
$qty=11;
$sql = "INSERT INTO new_customer (user_id,value1,value2) VALUES";
for($i=0;$i< $qty;$i++){
$sql .= "($new_id,'1','0')";
if($i < ($qty -1 )){
$sql .=",";
}
}
}
I'm not sure if this is correct way of doing this. After user is successfully registered I'm trying to get lastInsertId and loop and insert 10 new rows in new_customer table.
What is happening is that user is successfully registered but nothing is saved in new_customer. What is the problem here?
You need to execute your inner query like below:-
$conn->query($sql);
Add it after inner for loop code.
Also if you are using mysqli_* then you need to use mysqli_insert_id:-
$new_id = $db_con->mysqli_insert_id;

mysql insert into creates 2 records in table row

Ok .. I'm stuck. I tried several codes from topics here, but still not working for me so I need a little help please.
I want to log if a user is logged in for the first time and want to update that same record if the user returns. The update part works, but when my function is executed the first time, it insert a total blank record and a record with all the data provided by variables. The last_login column is NULL for the first vist and is nicely updated with the last login.
But what I can't figure out is why the first login creates these extra records.
Here is the function code I created:
function log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress)
{
global $connection;
$sql = mysqli_query($connection, "SELECT * FROM logfile_sap WHERE user_id = '{$userId}'");
if(mysqli_num_rows($sql) > 0)
{
$sql = "UPDATE logfile_sap SET last_login = NOW() WHERE user_id = '{$userId}'";
$query = mysqli_query($connection, $sql);
}
else
{
$sql = "INSERT INTO logfile_sap
(user_id, username, achternaam, district, gemeente, ipaddress, first_login)
VALUES
('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW())";
$query = mysqli_query($connection, $sql);
}
}
So as you can see I am checking if the user already exists in the logfile_sap table and if it does NOT exist I want to insert the user (which works but with an extra row) and if the user already exists the record is updated.
This is the code I use on top of the page that needs to check and adds the data in the table:
<?php log_users($userId, $username, $achternaam, $district, $gemeente, $ipaddress); ?>
I hope some has a brighter idea than me ;-)
++++++++++++++++++++++++++++++++++++++++++++
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!
Problem SOLVED. I had an epiphany !!!
I called my function OUTSIDE my if(isset($_SESSION['id'])) statement.
After I've put it INSIDE the if(isset($_SESSION['id'])) statement, there was only one record inserted into the table !!

How do I find out a specific row ID from a table?

Hello I’m working on a project (I’m a total newbie), here ‘s how the project goes…
I’ve created a Create User page, the user puts in the credentials and click on Create Account.
This redirects to another page (process.php) where all MySQL queries are executed-
Note: ID is set to Auto Increment, Not Null, Primary Key. All the data is inserted dynamically, so I don’t know which Username belongs to which ID and so on.
$query = “INSERT INTO users (Username, Something, Something Else) VALUES (‘John’, ‘Smith’, ‘Whatever’ )”
Everything gets stored into the “users” table.
Then it gets redirected to another page (content.php) where the User can review or see his/her credentials.
The problem is, I use SELECT * FROM users and mysql_fetch_array() but it always gives me the User with ID = 1 and not the current User (suppose user with ID = 11). I have no idea how to code this.
There are suppose 50 or more rows,
how can I retrieve a particular row if I don’t know its ID or any of its other field’s value?
You may use:
mysql_insert_id();
Get the ID generated in the last query. Reference: http://us1.php.net/mysql_insert_id
This function return the ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.
Now you have the id, add that to your WHERE clause.
Note: It would be better if you use mysqli.
You are using mysql_fetch_array() just once, so it is getting you just one row.
what you are writing:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
echo(row['id']);
?>
What should be there to fetch all the rows:
<?php
include('connection.php'); //establish connection in this file.
$sql = "select * from users";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo(row['id']);
}
?>
Now, what you need, is to get the user id of the registered user at that time.
For that, you need to create a session. Add session_start(); in your process.php and create a session there. Now to get the last id you have to make a query:
select *
from users
where id = (select max(id) from users);
Now this will give you the last id created. Store that in a session variable.
$_SESSION['id']=$id;
Now, on content.php add this:
session_start();
echo($_SESSION['id']);
You have to use WHERE:
SELECT * FROM users WHERE ID = 11
If you dont use WHERE, it will select all users, and your mysql_fetch_assoc will get you one row of all (ie. where ID = 1).
PS: mysql_* is deprecated, rather use mysqli_*.
Using mysql_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysql_query($query) or die( mysql_error() );
$user_id = mysql_insert_id();
header("Location: content.php?id=".$user_id);
Or another way to pass $user_id to your next page
$_SESSION['user_id'] = $user_id;
header("Location: content.php");
Using mysqli_ commands:
$query = "INSERT INTO users (`Username`, `Something`, `Something Else`) VALUES ('John', 'Smith', 'Whatever' )";
$result = mysqli_query($dbConn, $query) or die( printf("Error message: %s\n", mysqli_error($dbConn)) );
$user_id = mysqli_insert_id($dbConn);

how to add a if confition to a mysql query?

i am trying to add an if statement to a mysql query so that it checks the user exists from a table called ptb_users in the user_id column before the query runs.
users can write on other users walls and before a user can write on a users wall / before the query inserts into ptb_wallposts, i want it to check that the from_user_id = the ptb_users.user_id.
i am trying to do this but i get syntax errors all over my page can someone please can someone show me how i would need to structure this:
<?php
// check if the review form has been sent
if(isset($_POST['review_content']))
{
$content = $_POST['review_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['review_content']!='')
{
if exists (select user_id from ptb_users where user_id = #id)
begin
{
$sql = "INSERT INTO ptb_wallposts (id, from_user_id, to_user_id, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$profile_id."', '".$content."');";
mysql_query($sql, $connection);
$_SESSION['message']="<div class=\"infobox-wallpost\"><strong>Wall Post Added</strong> - Your comment was posted to {$profile[2]}'s wall.</div><div class=\"infobox-close4\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} }
}
end
else
begin
echo "error user doesnt exist"
end
?>
Here's an example of if statement (from MySQL Reference)
IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF
Let me explain a little more better, i'll compare between PHP and SQL if statements
PHP:
IF(variable > 0){
anything..
}
SQL:
IF variable > 0 THEN anything..
Read more:MySQL Reference - IF STATEMENT

PHP & SQL Insert data Into Table1 if input data exists in Table2

I've been trying to figure out how to insert data received from a form into one table only if the received data exists in another table. If the data doesn't exist it moves onto another query and checks another table for the received data.
This is what I'm trying to do:
function addNewUser($username, $password, $email, $actcode){
$time = time();
$q = "UPDATE ".TBL_RELEASE_CODES." SET code = '$actcode' WHERE code = '$actcode'";
$result = mysql_query($q, $this->connection);
if (!$result || (mysql_numrows($result)) == 0){
$q = "INSERT INTO ".TBL_RELEASE_USERS." VALUES ('$username', '$password', '0', $ulevel, '$email', '$actcode', $time)";
return mysql_query($q, $this->connection);
}
The purpose of this is that when the user submits a special code the system will run checks to see if the code belongs to a certain table.
If it finds the submitted code in a table it will run the insert query associated with the check, if not then it breaks and returns an error saying no match was found.
I'm probably using the code incorrectly as I've been scrounging information from Google searches and testing them out. With no luck yet.
This code is being run off a website using PHP 5 and MySQL.
The first query doesn't do anything -- it sets code to $actcode only in the rows where code is already $actcode. You should use a SELECT, not UPDATE:
$q = "SELECT COUNT(*) FROM ".TBL_RELEASE_CODES." WHERE code = ?";
$stmt = mysqli_prepare($this->connection, $q);
mysqli_stmt_bind_param($stmt, 's', $actcode);
mysqli_stmt_bind_result($stmt, $count);
mysqli_execute($stmt) or die "Query failed: ".mysqli_stmt_error($stmt);
mysqli_stmt_fetch($stmt);
if ($count == 1) {
// Insert into TBL_RELEASE_USERS
} else {
// Return error saying no match found
}
You should also not use the mysql_XXX functions. They're deprecated and make it hard to avoid SQL-injection attacks. My code above uses mysqli_XXX, which supports prepared statements to protect against that. It also has an OO-style API if you like, but I didn't use that above.

Categories