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.
Related
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);
}
I've now been trying for hour and can't figure the problem out. I've made a php file that fetch all items in a table and retrieves that as JSON. But for some reason after I inserted the second mysql-query, it stopped fetching the first item. My code is following:
...
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
$row2 = $result2->fetch_assoc();
while($row = $result2->fetch_assoc()) {
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,
strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
Any help is greatly appreciated.
EDIT: Thanks for all those super fast responses.
First you're fetching a row:
$row2 = $result2->fetch_assoc();
Then you start looping at the next row:
while($row = $result2->fetch_assoc()) {
If you want to loop over all of the rows, don't skip the first one. Just loop over all of the rows:
$result2 = // your very SQL-injectable query
while($row2 = $result2->fetch_assoc()) {
$result3 = // your other very SQL-injectable query
$row3 = $result3->fetch_assoc();
// etc.
}
Note that errors like this would be a lot more obvious if you used meaningful variable names. "row2", "result3", etc. are pretty confusing when you have overlapping levels of abstraction.
Important: Your code is wide open to SQL injection attacks. You're basically allowing users to execute any code they want on your database. Please look into using prepared statements and treating user input as values rather than as executable code. This is a good place to start reading, as is this.
No Need of $row2 = $result2->fetch_assoc();
<?
case "LoadEntryList":
$result2 = performquery("SELECT * FROM Entries WHERE Category = '" . $_POST["Category"] .
"' LIMIT " . $_POST["Offset"] . ", " . $_POST["Quantity"] . "");
while($row = $result2->fetch_assoc())
{
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row["UserID"] . "'");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
?>
Or,
<?
...
case "LoadEntryList":
$Category=$_POST["Category"];
$Offset=$_POST["Offset"];
$Quantity=$_POST["Quantity"];
$result3 = performquery("SELECT Entries.*, Users.Username FROM Entries, Users WHERE Entries.Category=$Category AND Entries.UserID=Users.ID LIMIT $Offset, $Quantity");
$row3 = $result3->fetch_assoc();
echo substr(json_encode($row),0,strlen(json_encode($row))-1) . ",\"Username\":\"" . $row3["Username"] . "\"}";
}
...
?>
I have a addition to David answer(can't comment on it yet)
This line of code:
$result3 = performquery("SELECT Username FROM Users WHERE ID = '" . $row2["UserID"] . "'");
will always return with the same result. If you were to change $row2[... into $row[... the code would take the rows that get updated by the while loop.
I am not content with the accepted result. The snippet can be fixed / replaced, and also a bad code must be replaced. Also not to mention is that I don't know if anyone spotted a really big mistake in the output. Here is the fix and I'll explain why.
$JSON = array();
$result2 = performquery( '
SELECT
e.*, u.Username
FROM Entries AS e
LEFT JOIN Users AS u ON u.ID = e.UserID
WHERE
e.Category = ' . $_POST['Category'] . '
LIMIT ' . $_POST['Offset'] . ', ' . $_POST['Quantity'] . '
' );
while( $row2 = $result2->fetch_assoc() ){
$JSON[] = $row2;
}
echo json_encode( $JSON );
Obviously the main issue is the query, so I fixed it with a LEFT JOIN, now the second part is the output. First it's the way you include the username, and the second what if you had multiple results? Than your output will be:
{"ID":1,"Username":"John"}{"ID":2,"Username":"Doe"}
How do you parse it? So the $JSON part comes in place. You add it to an array and will encode that array. Now the result is:
{["ID":1,"Username":"John"],["ID":2,"Username":"Doe"]}
LE: I left out the sql inject part which as stated by the OP, will be done afterwards? I'm not sure why not do it at the point of writing it, because you may forget later on that you need to sanitize it.
Below is my small code for inserting some info into AthleteID. It doesn't actually insert the information to the table though, any help is appreciated. (sorry for asking twice, but I think my first question isn't addressing whatever issue is holding me up here!)
<?php
require_once('resources/connection.php');
echo 'hello noob' . '<br />';
$query = mysql_query('SELECT LName, MyWebSiteUserID FROM tuser WHERE MyWebSiteUserID = MyWebSiteUserID');
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebSiteUserID"];
$update = "UPDATE `tuser` SET `AthleteID`='$athleteId' WHERE `MyWebSiteUserID` = `MyWebSiteUserID`;";
while($row = mysql_fetch_array($query)){
mysql_query( $update);
}
Where to begin..
1) Your using mysql and not mysqli. mysql is now deprecated but you could be on a PHP 4 system so keep that in mind.
2) You are building the $athleteID before you have found out what LName and SkillshowUserID is.
3) Your using a where of 1 = 1. You dont need this as it will return true for every row.
4) So...
// Execute a query
$results = mysql_query('SELECT LName, MyWebsiteID FROM tuser WHERE SkillshowUserID = SkillshowUserID');
// Loop through the result set
while($row = mysql_fetch_array($query))
{
// Generate the athleteId
$athleteId = strtoupper(substr($row["LName"], 0, 2)) . $row["MyWebsiteID"];
// Generate an sql update statement
$update = "UPDATE `tuser` SET `AthleteID`='" . $athleteId . "' " .
" WHERE LName = '" . $row['LName'] . "' " .
" AND MyWebsiteID = '" . $row['MyWebsiteID'] . "';";
// Fire off that bad boy
mysql_query($update);
}
I have had a long road to get to this last question. Everything is my code is working now, but I can't get this last little issue. Right now I have:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$val = $row["value_sum"];
$plan = $row["currentplan"];
$remain = $plan - $val;
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
It only subtracts the first value as opposed to the values for all. displayed like this:
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td>".$remain . " MB</td> ";
echo "<td>".$row['email'] . "</td></tr>";
}
So my goal is to subtract all value_sums from all dataplans, but what I have now, gives me the first value for all columns. Thank you!
mysql_fetch_assoc() will always get one row. You can use it in loop, or better use PDO, eg. like this:
$sql = "SELECT phonenumber,email, dataplan AS currentplan, SUM(datamb) AS
value_sum FROM maindata GROUP BY phonenumber, dataplan";
$results = $pdo->query($sql);
You can read about creating PDO connections here http://www.php.net/manual/en/book.pdo.php
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