I need to send the values of username, password, mail, first name and last name into two different tables in my database. I have made that possible with this code, and i get the values correct. I have one problem tho. When the user-info goes into "users" table, it auto-generates one userId. That same userId i need to use and put into the other table "usermeta" to connect the information to the correct user. What happens now is that i get a userId in the users table, but in the usermeta table the userId is = 0 on all new users. Can anyone help me?
if (isset($_POST['username']) and isset ($_POST['password'])) {
$username = $mysqli->real_escape_string($_POST['username']);
$password = md5($mysqli->real_escape_string($_POST['password']));
$email = $mysqli->real_escape_string($_POST['mail']);
$fname = $mysqli->real_escape_string($_POST['fname']);
$lname = $mysqli->real_escape_string($_POST['lname']);
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
$q = <<<END
INSERT INTO usermeta(first_name,last_name)
VALUES('{$fname}','{$lname}')
END;
if ($mysqli->query($query) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
if ( $mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
header('Location:home.php');
}
}
I got a form further down in the code that the info comes from that's going to the database, but it's the php-code that makes the error i assume to i exclude that code.
Thanks!
EDIT:
I've tried to implement your different comments. Thanks alot for the answers!
If i try to get the latest id inbetween the $query and $q, the output is 0. If i use the command:
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
echo $last_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
I get the correct id. But how can i use that variable to the new $q? It seems that the function breaks after the if is done.
Thanks! :)
You can use LAST_INSERT_ID() to retrieve the value of the auto-increment id that was created in your last insert. (Docs here)
So try:
$q = <<<END
INSERT INTO usermeta(first_name,last_name, userId)
VALUES('{$fname}','{$lname}', LAST_INSERT_ID();)
END;
Okey i managed to get it done. Thanks guys for the help!
The working code looks like this:
$query = <<<END
INSERT INTO users(username,pass,email,admin)
VALUES('{$username}','{$password}','{$email}','{$_POST['admin']}')
END;
if ($mysqli->query($query) === TRUE) {
$last_id = $mysqli->insert_id;
} else {
echo "Error: " . $query . "<br>" . $mysqli->error;
}
$q = <<<END
INSERT INTO usermeta(first_name,last_name, user_id)
VALUES('{$fname}','{$lname}','{$last_id}')
END;
if ($mysqli->query($q) !== TRUE) {
die("Could not query database" . $mysqli->errno . " : " . $mysqli->error);
}
Related
Here is the answer to moving some data from one table to another it may not be the best, but it does work.
$result = mysqli_query($con,"SELECT * FROM Teacher_staff");
while($row = mysqli_fetch_array($result))
{
// you don't need this step but it checks the select data portion
echo $row['First'] . " " . $row['Last'] . " " . $row['Id'];
// assign your variables, might not need this step as well
$First = $row['First'];
$Last = $row['Last'];
$id = $row['Id'];
// takes the information from the first mysqli and inserts it into the second table.
$sql="INSERT INTO teachers (First, Last, Id)
VALUES
(
'".addslashes($First)."',
'".addslashes($Last)."',
'".addslashes($Depart)."',
'".addslashes($id)."'
)";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
// confirms that each record is added to the table.
echo "1 record added";
}
echo "<br>";
mysqli_close($con);
echo "done";
Any way thanks for the help.... oh and I fixed it so that " ' " doesn't give an error.
Try this query.
$result = mysqli_query($con, "INSERT INTO Teachers (First, Last, Depart) SELECT First, Last, Depart FROM Teacher_staff");
That's literally all you should have to run.
If you have access to your database outside of PHP (phpMyAdmin or command line), I'd recommend running that query from there.
I am trying to delete a record in a MYSQL database when I need to select two simultaneous columns with the WHERE clause:
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if ($result3==false) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
When I execute this statement $result3 returns true but the entry is not deleted. What do I need to change in my formatting? The strings echo back correct data entered in the table.
Shouldn't it be,
"DELETE from Waiting WHERE ToUser = '" . $ToEmail . "' AND ImageID = '" . $ToEmailDB . "'"
$result3 = mysqli_query($con, "DELETE FROM Waiting WHERE ToUser='".$ToEmail."' AND ImageID='".$ToEmailDB."' ");
The query will return true if the SQL query executes successfully, even when the DELETE didn't remove any rows in the DB.
http://php.net/manual/en/mysqli.affected-rows.php
To answer your question, you need to find the number of rows affected
$result3 = mysqli_query($con, " DELETE FROM Waiting WHERE ToUser='$ToEmail' AND ImageID='$ToEmailDB' ");
if (!$result3) {
echo "A database error occurred";
}
else if (mysqli_affected_rows($con) == 0) {
echo "No images waiting for " . $ToEmail . " for image " . $ToEmailDB;
}
else {
echo "Image and record deleted for " . $ToEmail . " for image " . $ToFileName . ".jpg and record " . $GuessImageID;
}
Your query always returns TRUE if its executed successfuly. Only on query failures it returns FALSE As per the PHP documentation:
mysqli_query() Returns FALSE on failure. For successful SELECT, SHOW,
DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
For other successful queries mysqli_query() will return TRUE.
From Moby04's Comment
If you want to check if something was actually deleted use mysqli_affected_rows() function.
I am looking to post data into two database tables from a single form.
My databases are arranged as below:
Database 1 - 'watchlists':
watchlist_id
user_id
name
description
category
Database 2 - 'watchlist_films':
watchlist_id
film_id
My current MySQL query looks like this: $query = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$watchlist_name['watchlist_id']', '$rt_id') WHERE watchlists ('watchlist_id') = " . $watchlist_name['watchlist_id'];, but I'm not sure if there's got to be some form of INNER JOIN somewhere?
Not sure what other information/code to provide, so I apologise if there's too little detail here, but, if there's anything else which is needed, just drop me a comment and I'll put up anything else which is required. I'm a relative PHP newbie, so apologies if this seems like a really simple question!
Update based on comments:
I have now got half of my query working, and have updated the logic to reflect it. The new query is basically doing the following:
INSERT new Watchlist to 'watchlists' table
SELECT watchlist_id of new Watchlist from 'watchlists' table WHERE watchlist_name = $watchlist_name (name of new Watchlist just created) and user_id = $user_id
INSERT watchlist_id (selected from previous query) AND film_id into 'watchlist_films' table
based on your comments, my queries now look like so:
if ($submit == 'Submit') {
require_once("db_connect.php");
$watchlist_name = clean_string($_POST['watchlist-name']);
$watchlist_description = clean_string($_POST['watchlist-description']);
$watchlist_category = $_POST['watchlist-category'];
$addWatchlist_bad_message = '';
$addWatchlist_good_message = '';
if ($db_server) {
if (!empty($watchlist_name)) {
$watchlist_name = clean_string($watchlist_name);
$watchlist_description = clean_string($watchlist_description);
mysql_select_db($db_database);
// Insert new Watchlist into Watchlist index
$insert_new_watchlist = "INSERT INTO watchlists (user_id, name, description, category) VALUES ('$user_id', '$watchlist_name', '$watchlist_description', '$watchlist_category')";
mysql_query($insert_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $insert_new_watchlist);
// Select new Watchlist ID
$select_new_watchlist = "SELECT watchlist_id FROM watchlists WHERE name = " . $watchlist_name;
$new_watchlist_id = mysql_query($select_new_watchlist) or die("Insert failed. " . mysql_error() . "<br />" . $select_new_watchlist);
// Add film to new Watchlist
$add_new_film = "INSERT INTO watchlist_films (watchlist_id, film_id) VALUES ('$new_watchlist_id', '$rt_id')";
mysql_query($add_new_film) or die("Insert failed. " . mysql_error() . "<br />" . $add_new_film);
$addWatchlist_good_message = '<div class="alert alert-success">Watchlist created successfully!</div>';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
} else {
$addWatchlist_bad_message = '<div class="alert alert-error">Error: could not connect to the database.</div.';?>
<script>
$('a.add-watchlist').trigger('click');
</script><?php
}
require_once("db_close.php");
}
My query, however, seems to be failing at the SELECT statement, in between adding the new Watchlist to the Watchlist index and adding the film to the newly created Watchlist.
try this
$query1 = "INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')";
$query2= "INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")";
$result = mysqli_multi_query($query1, $query2);
You will need to write an INSERT for each table.
$mysqli->query("INSERT INTO watchlist_films (watchlist_id, film_id)
VALUES ('" . $watchlist_name['watchlist_id'] . "', '$rt_id')");
$mysqli->query("INSERT INTO watchlists ('watchlist_id')
VALUES (" . $watchlist_name['watchlist_id'] . ")");
That's the function which I'm using to print the contents of 'username' table:
function showtable()
{
ob_start();
$db = new PDO("sqlite:test.db");
$query = "SELECT * FROM " . $_SESSION['username'] . " ORDER BY `a` DESC;";
$result = $db->prepare($query);
$result = $db->query($query);
print "<table>";
print "<tr><td>First Column</td><td>Second Column</td><td>Third column</td></tr>";
foreach ($result as $row)
{
print "<tr><td>" . $row['a'] . "</td><td>" . $row['b'] . "</td><td>Here stays the button</td></tr>";
}
print "</table>";
unset($db);
ob_end_flush();
}
So, how should look a function so when creating each row of the html table, a button for updating the corresponding sqlite table row is inserted in the third cell (named 'Here stays the button' for easier reading)? I'm calling my function when opening the test.php (with added required_once('functions.php')) file in main browser window, nothing special in that.
That's the UPDATE query:
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = " . $row['a'] . ";";
a column is integer primary key
b column is text
c column is integer, all fields hold 0 value
P.S. Don't talk about AJAX, I'm not ready for it (and don't like it, a lot of pages that use AJAX lag the browser). Just asking for ideas about a simple php function, that adds UPDATE TABLE functionality through buttons for each row.
Thanks in advance :)
What is the updating for? what will happen if C = 1?
anyway for your question, my suggestion is to use an anchor tag.
i.e
in the "Here stays the button" will be Update
in your test.php
if($_GET['a_new'] != '')
{
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = ".$_GET['a_new']."";
}
p.s you have excess ";" in your query. you only add the query on the end of the query statement not inside it i.e $sql = "select * from"; not $sql = "select * from;";
This is definitely a beginner's question. There are two issues. The id in my MYSQL table (set to autoincrement) keeps going up, even though I delete rows from my table (I'm using phpmyadmin). As for the other issue, I can't seem to find a way to work with the row most recently entered by the user. The code echos all existing rows from MYSQL.
I've bolded the most pertinent section of code.
<?php
//establish connection to mysql
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
/*retrieve user input from input form
and initialize variables */
$Word1 = $_POST["Word1"];
$Word2 = $_POST["Word2"];
$Word3 = $_POST["Word3"];
$Word4 = $_POST["Word4"];
$Word5 = $_POST["Word5"];
//select db
mysql_select_db("madlibs", $con);
//insert user input for word 1
$sql = "INSERT INTO test (Word1, Word2, Word3, Word4, Word5)
VALUES
('$Word1', '$Word2', '$Word3', '$Word4', '$Word5')";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query ("SELECT * FROM test");
/* take note here */
while($row = mysql_fetch_array($result))
{
echo $row['Word1'] . " " . $row['Word2'] . " " . $row['Word3'] . " " .
$row['Word4'] . " " . $row['Word5'] . " " . $row['id'];
echo "<br />";
} /* take note here */
mysql_close($con);
?>
$result = mysql_query ("SELECT * FROM test order by id desc limit 1");
As for your id question...that's how ids work. They don't fill in gaps.
On a side note: Never ever put user submitted data directly into the query string. Always escape them with mysql_real_escape_string().
SELECT * FROM test ORDER BY Id DESC LIMIT 1