GET ID after submitting form - php

Im trying to get the ID when I insert a SQL, I've tried to get the last. I've tried to echo out the ID in the hidden html form but without any success
As you see I've $sql that inserts INTO log_create, but from that I need to receive the ID which is created, it need to be echoed
$id = $db->real_escape_string(trim($_POST['id']));
$name2 = preg_replace('/\s+/', '', $name);
$game = $db->real_escape_string(trim($_POST['game']));
$info = $db->real_escape_string(trim($_POST['info']));
$mobname = $db->real_escape_string(trim($_POST['mobname']));
$sql = "INSERT INTO log_create(`id`, `name`, name2, game, monster, info)VALUES('$id', '$name', '$name2', '$game', '$mobname', '$info')";
if($result=$db->query($sql))
{
$log = $db->query("SELECT itemname FROM `log_mitem` WHERE mobname = '".$mobname."' AND game = '".$game."'") or die($db->error);
if($log1 = $log->fetch_object());
{
while($loco = $log->fetch_object())
{
$item = "$loco->itemname";
$logss = "INSERT INTO log_drops(`item`, `mobname`, `game`, `log_id`, `log_name`)VALUES('$item', '$mobname', '$game', '$id', '$name')";
if($result1 = $db->query($logss));
}
}
echo '<p>';
echo 'Your droplog has been created! Check your droplog category to start hunting!';
echo '</p>';
} else { echo 'Something went wrong!';
}

Thismay help you, maybe?
Good luck! :-)
EDIT: My bad, I should have said what was that, instead of linking directly.
It's the mysqli::$insert_id variable.
It stores the last ID created by the last used "INSERT" sentence.
...
if($result=$db->query($sql))
{
echo "New ID: "+$db->insert_id+"<br />";
...
Or wherever you want to use it.
Make sure to store it before inserting anything else, or it'll be replaced.

Related

echo results from a SELECT query from a function thats in another file

First time asking on here so please bear with. I apologise if this questions is asked elsewhere, if so please link the answer.
I have two files, one called profile.php and another called functions.php, the functions file is linked and works fine.
My question is / is it possible to return the results as an array from functions.php and use them in profiles.php and how to do so. I've looked high and low and have probably read the answer but failed to understand it.
//functions.php
function playerSQL($memberid) {
if (isset($memberid)) {
global $connect_db;
$playerSQL = "SELECT memberID AS memberID, membershipType AS membershipType, firstName AS firstName, lastName AS lastName, DOB AS DOB, profileImage AS profileImage, shortBio AS shortBio, background AS background, battingStyle AS battingStyle, bowlingStyle AS bowlingStyle, playCricketID AS playCricketID, sponsor.sponsorImage AS personalSponsor, sponsor.sponsorURL AS personalSponsorURL FROM members LEFT JOIN sponsors AS sponsor ON (sponsor.sponsorID = members.personalSponsor) WHERE memberID = " . $memberid;
print_r($playerSQL); // Check sql is correct
$result = mysqli_query($connect_db,$playerSQL);
$player = mysqli_fetch_array($result,MYSQLI_ASSOC);)
// print_f works from here and returns as expected
printf ("%s %s\n",$player["lastName"],$player["firstName"]);
}// CLOSE IF
} // CLOSE FUNC
This prints the last name and first name correctly when the function is called.
// profile.php
require_once('includes/dbfixtures_conn.php');
include_once('includes/functions.php');
if (isset($_GET['mid'])) {
$memberid = (int)$_GET['mid'];
}
playerSQL($memberid);
echo 'The Members first name is ' . $player['firstName'];
echo 'The Members last name is ' . $player['lastName'];
Is it / how is it possible to use like this.
You need to return the data and store in another variable so that you can access it later on
function playerSQL($memberid) {
if (isset($memberid)) {
global $connect_db;
$playerSQL = "SELECT memberID AS memberID, membershipType AS membershipType, firstName AS firstName, lastName AS lastName, DOB AS DOB, profileImage AS profileImage, shortBio AS shortBio, background AS background, battingStyle AS battingStyle, bowlingStyle AS bowlingStyle, playCricketID AS playCricketID, sponsor.sponsorImage AS personalSponsor, sponsor.sponsorURL AS personalSponsorURL FROM members LEFT JOIN sponsors AS sponsor ON (sponsor.sponsorID = members.personalSponsor) WHERE memberID = " . $memberid;
print_r($playerSQL);
$result = mysqli_query($connect_db,$playerSQL); // resolved syntax error
$player = mysqli_fetch_array($result,MYSQLI_ASSOC);
return $player; // returned data
}
}
$player = playerSQL($memberid);
if ($player) { // check whether data is present or not
echo 'The Members first name is ' . $player['firstName'];
echo 'The Members last name is ' . $player['lastName'];
}
else {
echo 'no data available';
}
Also, you had syntax error on line:
$player = mysqli_fetch_array($result,MYSQLI_ASSOC);)
Instead of printf in function use return.
ex: return $player;
in your profile.php file update the function call and return variable as mentioned below.
$urvariable_name=playerSQL($memberid);
echo 'The Members first name is ' . $urvariable_name['firstName'];
echo 'The Members last name is ' . $urvariable_name['lastName'];

Why are my variables not updating in a php mysqli for-loop?

I am trying to sort a single table (of 10k+ rows) into two separate tables, but seem to be running into a nonsense error that I can't figure out. When i comment out the mysqli insert statements, the variables are printing out correctly and updating as they should. I can see all of the data with the correct keys and values even when looping through all the values in the table.
When I add in the insert statement and place it in a mysqli_query, however, I am suddenly getting tons of mysqli errors saying that there are suddenly duplicate primary keys, but as per the previous tests, there are no duplicates. Other times, it seems to only loop once and then stop (or loop the correct amount of times, but doing nothing each time. I have printed out the mysql statements and was able to see that they were all correct before attempting the query, and yet it still causes issues when actually running. The code in its entirety is included below, but I cannot figure out what the issue is for the life of me.
$sql = "SELECT * FROM originalTable ORDER BY port LIMIT 20";
$result = mysqli_query($conn, $sql);
$num_Rows = mysqli_num_rows($result);
echo $num_Rows."<br/>";
// gets data for each row in the table
for($i=0; $i<$num_Rows; $i++){
$row = mysqli_fetch_assoc($result);
$ID = $row["ID"];
echo $ID."<br/>";
$IP = $row["IP"];
echo $IP."<br/>";
$port = $row["port"];
echo $port."<br/>";
$running = $row["running"];
echo $running."<br/>";
$afk = $row["afk"];
echo $afk."<br/>";
$gamemode = $row["gamemode"];
echo $gamemode."<br/>";
$maxplayers = $row["maxplayers"];
echo $maxplayers."<br/>";
$spawnprotection = $row["spawnprotection"];
echo $spawnprotection."<br/>";
$whitelist = $row["whitelist"];
echo $whitelist."<br/>";
$enablequery = $row["enablequery"];
echo $enablequery."<br/>";
$enablercon = $row["enablercon"];
echo $enablercon."<br/>";
$rconpassword = $row["rconpassword"];
echo $rconpassword."<br/>";
$motd = $row["motd"];
echo $motd."<br/>";
$announceachieve = $row["announceplayerachievements"];
$allowflight = $row["allowflight"];
$spawnanimals = $row["spawnanimals"];
$spawnmobs = $row["spawnmobs"];
$forcegamemode = $row["forcegamemode"];
$hardcore = $row["hardcore"];
$pvp = $row["pvp"];
$difficulty = $row["difficulty"];
$generatorsettings = $row["generatorsettings"];
$levelname = $row["levelname"];
$levelseed = $row["levelseed"];
$leveltype = $row["leveltype"];
$autosave = $row["autosave"];
if($IP == $server1){
$server = "server1table";
$sql1 = "INSERT INTO server1table (id, ip, port, running, afk, gamemode, maxplayers, spawnprotection,
whitelist, enablequery, enablercon, rconpassword, motd, announceplayerachievements,
allowflight, spawnanimals, spawnmobs, forcegamemode, hardcore, pvp, difficulty,
generatorsettings, levelname, levelseed, leveltype, autosave) VALUES ('$ID', '$IP',
'$port', '$running', '$afk', '$gamemode', '$maxplayers', '$spawnprotection', '$whitelist',
'$enablequery', '$enablercon', '$rconpassword', '$motd', '$announceachieve', '$allowflight', '$spawnanimals',
'$spawnmobs', '$forcegamemode', '$hardcore', '$pvp', '$difficulty', '$generatorsettings', '$levelname',
'$levelseed', '$leveltype', '$autosave')";
echo $sql1;
$result = mysqli_query($conn, $sql1);
echo "Server 1<br/>";
if($result){
echo "Success?";
}
else{
echo "Failure = " . $conn->error;
}
} else if ($IP == $Server2){
$server = "server2table";
$sql2 = "INSERT INTO server2table (id, ip, port, running, afk, gamemode, maxplayers, spawnprotection,
whitelist, enablequery, enablercon, rconpassword, motd, announceplayerachievements,
allowflight, spawnanimals, spawnmobs, forcegamemode, hardcore, pvp, difficulty,
generatorsettings, levelname, levelseed, leveltype, autosave) VALUES ('$ID', '$IP',
'$port', '$running', '$afk', '$gamemode', '$maxplayers', '$spawnprotection', '$whitelist',
'$enablequery', '$enablercon', '$rconpassword', '$motd', '$announceachieve', '$allowflight', '$spawnanimals',
'$spawnmobs', '$forcegamemode', '$hardcore', '$pvp', '$difficulty', '$generatorsettings', '$levelname',
'$levelseed', '$leveltype', '$autosave')";
echo $sql2;
$result = mysqli_query($conn, $sql2);
echo "Server 2<br/>";
if($result){
echo "Success?";
}
else{
echo "Failure = " . $conn->error;
}
}
EDIT: The ID in the table above is not the table ID field or primary key. It represents the ID of the player. The port is the primary key of the table
Clarification: In one iteration of this code, it sent everything to server 1 with no issues, but it totally ignored server 2. I have since tested and ensured that the split (if statement) worked as intended, and it prints the correct server name and sets $sql to the intended value (as it prints out). It will only move the first column of the table and then it sets everything else to blank and the ID to 0 and sends a bunch of duplicate primary errors.
I don't think you should be inserting the IDs, that might be where you're fighting with possibly the table primary keys and auto_increment. Just remove the id from the insert and it should be fine. Depending upon how you've set up the table structure. Generally you shouldn't need to preserve the IDs, that's just there for uniqueness and indexing housekeeping etc.

PHP: Running mysql_query if data from $_POST matches data in table

I hope my title isn't completely confusing. I'd like to start by saying I am in now way a programmer and am an amateur with PHP and MySQL, which I use for online gaming. I have been tirelessly working at this for a few days, with no success. I've been toying with the idea of asking for help here, hoping folks go easy on me and don't completely rip apart my code! Like I said, I'm an amateur.
Basically, what I'm trying to do is match the $horsename data from my $_POST array with name in my table called horses. If they do not match it will add a horse with that name into the horses table. If they do match, it will simply continue on and add the data from the $_POST array into the results table for each line.
The issue I'm getting, (and I've toyed with this multiple times, with a different issue arising each time) is even if the $horsename matches name in the horses table, it tries to add a new horse into the horses table. It also is not moving onto the next line of data and will try to add the same horse over and over again. (Hope that makes sense!)
I'm pasting most of my code from this page below, just in case it's something earlier in my code causing this issue. Please note, a portion of this code is not my own and I am working on it for someone else, so if things are not completely uniform in a couple of spots, that is why. The portion I'm working on is what I've mentioned above.
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$results = str_replace("\r", '', trim($_POST['news']));
$data = array();
$lines = explode("\n", $results);
foreach ($lines as $place) {
if (!empty($place)) {
$data = array();
$detail = explode(",", $place);
if (!empty($detail)) {
$id = '';
$show = $_POST['show'];
$year = $_POST['year'];
$association = $_POST['association'];
$chpoints = $_POST['chpoints'];
$rchpoints = $_POST['rchpoints'];
$ttpoints = $_POST['ttpoints'];
$chearnings = $_POST['chearnings'];
$rchearnings = $_POST['rchearnings'];
$ttearnings = $_POST['ttearnings'];
$horsename = stripslashes(trim($detail[0]));
$placement = stripslashes(trim($detail[1]));
$class = stripslashes(trim($detail[2]));
if($placement === 'CH'){
$points = $chpoints;
}
else if ($placement === 'RCH') {
$points = $rchpoints;
}
else {
$points = $ttpoints;
}
if ($placement === 'CH') {
$earnings = $chearnings;
}
else if ($placement === 'RCH') {
$earnings = $rchearnings;
}
else {
$earnings = $ttearnings;
}
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
if (isset($_POST['news'])) {
$query="INSERT INTO `results` (`id`, `show`, `year`, `place`, `name`, `class`, `points`)
VALUES ('$id','$show','$year','$placement','$horsename','$class','$points')";
mysql_query($query) or die ('Error updating database: ' . mysql_error());
echo "Result successfully added!" ;
}
};
};
};
To take a snip-it from above, this is the place I'm having the issues:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}
}
If anything from the page where news is coming from is needed, please let me know.
Thanks in advance!
The problem is that you are querying the database for a list of every horse name. You're iterating through that list and each time the names don't match, you're inserting the new name. What you need to do instead is to query for the specific name.
SELECT * FROM horses WHERE name = '$horsename'
If this returns a row, then you know the horse is already in the database. If it returns no rows, then you can safely insert once. By the way, you'll want to properly escape your input to prevent SQL injections so don't use my code verbatim.
Try this:
$horses = mysql_query("SELECT name FROM horses") or die ('Error accessing database: ' . mysql_error());;
$i = 0;
$horsename = "";
while($row = mysql_fetch_array($horses)) {
$storedname = addslashes(trim($row['name']));
if ($storedname == $horsename) {
$i = 1;
}
}
if($i == 1) {
echo "The names do match for $horsename";
}
else {
echo "The names do not match for $horsename";
$addhorse="INSERT INTO horses (id, owned_by, name, yob, color, breed, discipline, sire, dam, damsire, bred_by, gender)
VALUES ('','25','$horsename','','','','','','','','','')";
mysql_query($addhorse) or die ('Error updating database: ' . mysql_error());
echo 'Added '. $horsename .' to Archive.';
}

MySQL & PHP Insert Query Failing

I know there isn't enough validation in here just going through some testing. $result always returns empty? Is my query bad? I'm new to PHP and concatenating variables into strings is not something I have grasped full. Going with the OOP form since I'm pretty familiar with it and the concepts.
Also, I know this code is terribly sloppy... just trying to dive right in =)
`
$page = new Page();
$page->title = "Add a New Item";
$page->DisplayHeader();
$page->DisplaySidebar();
if (isset($_POST['submit']))
{
// make short variable names
$name = trim($_POST['name']);
$level = intval($_POST['level']);
$slot = strtolower($_POST['slot']);
$hp = intval($_POST['hp']);
$mana = intval($_POST['mana']);
$mvs = intval($_POST['mvs']);
$int = intval($_POST['int']);
$wis = intval($_POST['wis']);
$str = intval($_POST['str']);
$dex = intval($_POST['dex']);
$con = intval($_POST['con']);
$p_ac = intval($_POST['p_ac']);
$m_ac = intval($_POST['m_ac']);
$saves = intval($_POST['saves']);
$hit = intval($_POST['hit']);
$dam = intval($_POST['dam']);
$queryOk = 1;
if (empty($name) || empty($level) || empty($slot))
{
echo '<h3>Please enter all the required fields</h3>';
$queryOk = 0;
}
// Instantiate database object and connect
# $db = new mysqli('*host*', '*user*', '*pass*', '*database*');
// Check connection to
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database, try again later';
}
$query = "INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)".
"V ALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
$result = $db->query($query);
if (!$result)
{
echo '<h3>Error: Item was not entered. (Your webmaster sucks)</h3>';
}
else {
echo "<p>The items \"$name\" was successfully entered into the database. <a href=\"equipment.php\>Back to Equipment or add another item.</a></p>";
}
$db->close();
}`
If the space in V ALUES is actually in your code that would cause your query to fail
UPDATE
If that isn't the cause of the error use $mysqli->error to see what error occurred.
if (!$result)
{
echo '<h3>'$mysqli->error' (Your webmaster sucks)</h3>';
}
int is a reserved word in mysql, and you're using it as a fieldname. You'll have to escape it with backticks:
INSERT INTO ... (..., `int`, ...)
^---^-- escapes
your query:
INSERT INTO items (name, level, slot, hp, mana, mvs, int, wis, str, dex, con, p_ac, m_ac, saves, hit, dam)
^^^^--- problem here
VALUES ('$name', $level, '$slot', $hp, $mana, $mvs, $int, $wis, $str, $dex, $con, $p_ac, $m_ac, $saves, $hit, $dam)";
^^^^^---NOT here

table updates empty spaces when user do not enter anything to the textbox

i am doing a project where one may update the name, position, department and tag of the employee.
But as i do my project, it wont update, i know there is something wrong with my code. would you guys mind checking it.
my php page has an index.php which is the main menu, if you click the employee name in the list, a pop up window will appear. that pop up is for updating.
my php code (it now updating) but errors found:
<?php
$con=mysql_connect('localhost','root','pss') or die(mysql_error());
mysql_select_db('intra',$con);
if(isset($_POST['submitted']))
{
$sql = "SELECT * FROM gpl_employees_list where emp_id='".$_POST['eid']."'";
$result = mysql_query($sql) or die (mysql_error());
if(!$result || mysql_num_rows($result) <= 0)
{
return false;
}
$qry = "UPDATE gpl_employees_list SET emp_nme = '".$_POST['ename']."', emp_pos = '".$_POST['pos']."', emp_dep = '".$_POST['dep']."', emp_tag = '".$_POST['tag']."' WHERE emp_id = '".$_POST['eid']."' ";
mysql_query($qry) or die (mysql_error());
?><script>window.close();</script><?php
}
?>
*NOTE : this is now updating, but if a user leaves one of the textboxes empty, it updates the table with empty spaces as well and that is my problem now. how do i avoid that? i mean if a user leaves one textbox empty,the data with empty values must still contain its old value,but how to do that with this code? thanks for those who will help
MisaChan
You use $_POST for 'name/pos/dep/tag' and $_GET for 'emp' so you're probably not getting the values.
Change the GETs to POST - that should do it.
Since you're updating, I'd recommend using POST over GET.
GET is more appropriate for searching.
Also, you can put all your update queries into one update query.
Like so.
$name = $_POST['name'];
$pos = $_POST['pos'];
$dep = $_POST['dep'];
$tag = $_POST['tag'];
$emp = $_POST['emp'];
$qry_start = "UPDATE gpl_employees_list SET ";
$where = " WHERE emp_id = $emp";
$fields = "";
$updates = "";
if($name){
$updates .= " `emp_name` = $name,";
}
if($pos){
$updates .= " `emp_pos` = $pos,";
}
if($dep){
$updates .= " `emp_dep` = $dep,";
}
if($tag){
$updates .= " `emp_tag` = $tag,";
}
$updates = substr($updates, 0, -1); //To get rid of the trailing comma.
$qry = $qry_start . $updates . $where;
this is what i used to keep it working :) i hope this could be a source for others as well :)
$col['emp_nme'] = (trim($_POST['ename']))?trim($_POST['ename']):false;
$col['emp_pos'] = (trim($_POST['pos']))?trim($_POST['pos']):false;
$col['emp_dep'] = (trim($_POST['dep']))?trim($_POST['dep']):false;
$col['emp_tag'] = (trim($_POST['tag']))?trim($_POST['tag']):false;
// add a val in $col[] with key=column name for each corresponding $_POST val
$queryString ="UPDATE `gpl_employees_list` SET ";
foreach($col as $key => $val){
if($val){
$queryString .="`".$key."`='".$val."',";
}
}
$queryString = substr($queryString ,0 ,strlen($queryString) - 1 )." WHERE emp_id = '".$_POST['eid']."'";
mysql_query($queryString);
After making changes to an SQL database, remember to commit those changes, otherwise they'll be ignored.

Categories