How to do a database check and depending on results either update or insert (keep getting a HTTP 500 error)How do I get PHP errors to display?Is there an easy way to skip updating a field to an empty value in a database?How to check database and, as a result, check a radio button?php script echoing part of the php instead of what intendedHow to Insert Multiple Checkbox Values into a DatabaseHow to insert dynamic multidimensional array in database with mysqlimysqli query results not getting inserted in the databaseDatabase does not get updated, But no error appears. MySQL and PHPhow to check id is existed before insert to databaseIf we have many inputs with same name how we can receive the value and insert into the database
I am getting "syntax error near unexpected token `'$#''" in a simple Bash script
Parallel resistance in electric circuits
How To Make Earth's Oceans as Brackish as Lyr's
What 68-pin connector is this on my 2.5" solid state drive?
simjacker: which SIMs are vulnerable?
If the gambler's fallacy is false, how do notions of "expected number" of events work?
Is Schwarzschild's solution in his original paper consistent with current solutions?
Why is my fire extinguisher emptied after one use?
In a hashmap, the addition of a new element to the internal linked list of a bucket is always at the end. Why?
What are uses of the byte after BRK instruction on 6502?
Is there any reason to concentrate on the Thunderous Smite spell after using its effects?
Output a Super Mario Image
Can druids change their starting cantrips each day?
Can I conceal an antihero's insanity - and should I?
Is there a tool to measure the "maturity" of a code in Git?
Diffraction of a wave passing through double slits
What is the name of this Allen-head furniture fastener?
In what sequence should an advanced civilization teach technology to medieval society to maximize rate of adoption?
What organs or modifications would be needed for a life biological creature not to require sleep?
Should you only use colons and periods in dialogues?
What explanation do proponents of a Scotland-NI bridge give for it breaking Brexit impasse?
Real mode flat model
Specific filter on the set using Python
What jurisdiction do Scottish courts have over the Westminster parliament?
How to do a database check and depending on results either update or insert (keep getting a HTTP 500 error)
How do I get PHP errors to display?Is there an easy way to skip updating a field to an empty value in a database?How to check database and, as a result, check a radio button?php script echoing part of the php instead of what intendedHow to Insert Multiple Checkbox Values into a DatabaseHow to insert dynamic multidimensional array in database with mysqlimysqli query results not getting inserted in the databaseDatabase does not get updated, But no error appears. MySQL and PHPhow to check id is existed before insert to databaseIf we have many inputs with same name how we can receive the value and insert into the database
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I am trying to build a way to do an input field update check that looks to see if a user input field is empty or not. And then depending on answer if it is empty or not do more checks. So for example if the input field is empty I want it to be ignored so rest of code runs, And if there is a value inside of the input field some more checks will be done to check if it is inside the database or not, and if it is not inside the database then it must be inserted into the database, and if it is already in then just update that field.
The table is a relational one to a main table where inf_id is the main table and userid is the relational one i am working in
So I have tried to do it in different way however I keep running into problems and each time I make a mistake or something that doesn't work I get a HTTP 500 error page saying it can't be reached. I have also tried to do a change the name in the input to other things to see if that effects and different layouts or such neither works I feel like it is something small that I am missing out on
also tired but i may have done it incorrectly since I never really used this before
IF EXISTS (SELECT count(*) FROM `table` WHERE inf_id = $infid)
BEGIN UPDATE GOES HERE END ELSE BEGIN INSERT GOES HERE END
This is my Code in the form to check the database has inputs, if it doesn't it creates a blank input. However If there is values in the database then it will echo it out
$vId = $_GET['i']; //this is the users unique ID that is send in the query string for testing purpose
if (mysqli_num_rows($rs_username) == 0 )
echo '<input type="text" name="currentusername[]" class="currentusername" placeholder="Current Bikes" >';
else
while ($rs_bike_rows = mysqli_fetch_assoc($rs_bikes))
echo '<input type="text" name="currentusername[]" class="currentusername" value="' . $row['currentusername'] . '">';
echo '<input type="hidden" name="userid[]" value="' . $row['userid'] . '">';
echo '<button type="button" onclick="return deleteFromDbBike('. $rs_bike_rows['oid'] .', '. $vId .');">Delete</button>';
This is to sanitize the inputs that the users inputs in a process file
if (isset($_POST['currentusername']) && $_POST['currentusername'] !== '')
$currentusername = $_POST['currentusername'];
$allusername = '';
foreach ($vcurrentbike as $users)
$allusername .= $users. ' ';
if (filter_var($allusername , FILTER_SANITIZE_STRING) === null)
$vValidation++;
else
$currentusername= '';
later on in the process file to then check the input value and update/insert it
$user = $_POST['userid'];
if ($currentusername != '')
for ($i = 0; $i < count($user); $i++)
$userid = $bike[$i];
$valueuser = $currentusername[$i];
$sqlcheck = "Select `inf_id` FROM usertable WHERE inf_id = $vId";
$resultcheck = mysqli_query($conn,$sqlcheck);
if (mysqli_num_rows($resultcheck) >= 1)
$stmt = $conn->prepare("UPDATE usertable SET currentusername = ? WHERE inf_id = ? and userid = ?");
$stmt->bind_param("sii", $currentperson, $infid, $ownedid);
$currentperson = $valueuser ;
$infid = $vid;
$ownedid = $userid;
$stmt->execute();
//the update code works (tried and tested) just using
//exit to see where the code goes.
exit('1');
else
//this is where the insert value would be however I can
//never get it to echo 0 when it exits; instead i just get a HTTP 500;
exit('0');
;
else
exit('fails');
In the End I want it to be able to check if the user has inputted values and then depending on if they have or have not then either insert or update it. and if the user hasn't just ignore it. and move onto the next field
Edit
it basically has 2 levels to this statement
Level 1:
1.1) if user input is empty then ignore it completely.
1.2) if user input has a value check it against the database
Level 2:
2.1) if the value exists in database then update the values
2.2) if the values don't exists then insert it into the database.
Error I'm running into is that if the value is not in the database to begin with it will create an empty input field.
Now when a user then adds text to the empty field it wants to update it but it doesn't exists. so through out errors at me as there is nothing to update
The States of the input field can be :
1) empty with no value at all
2) Has a value now added so it is not in the db
3) has a value from initial submission of form that is in db
EDIT 2: add more button
<button type="button" onclick="addMoreRows('user')"> Add More Current Usernames</button>
<div id="currentuser"></div>
var itemTypes =
user:
maxLimit: 4,
currentCount: 1,
selector: '#currentuser',
newElement: '<div class="moreusersadd"><input type="text" name="currentusernameadd[]" class="currentusernameadd" placeholder="Current Bikes" ><button class="delete" onclick="deleteRow(this, 'user')">Delete</button></div>'
function addMoreRows(type)
var item = itemTypes[type];
if (item.currentCount < item.maxLimit)
item.currentCount++;
$(item.selector).append(item.newElement);
else
alert('You Have Reached the limits')
function deleteRow(event, type)
$(event).parent('div').remove();
itemTypes[type].currentCount--;
;
php mysqli sql-update
add a comment
|
I am trying to build a way to do an input field update check that looks to see if a user input field is empty or not. And then depending on answer if it is empty or not do more checks. So for example if the input field is empty I want it to be ignored so rest of code runs, And if there is a value inside of the input field some more checks will be done to check if it is inside the database or not, and if it is not inside the database then it must be inserted into the database, and if it is already in then just update that field.
The table is a relational one to a main table where inf_id is the main table and userid is the relational one i am working in
So I have tried to do it in different way however I keep running into problems and each time I make a mistake or something that doesn't work I get a HTTP 500 error page saying it can't be reached. I have also tried to do a change the name in the input to other things to see if that effects and different layouts or such neither works I feel like it is something small that I am missing out on
also tired but i may have done it incorrectly since I never really used this before
IF EXISTS (SELECT count(*) FROM `table` WHERE inf_id = $infid)
BEGIN UPDATE GOES HERE END ELSE BEGIN INSERT GOES HERE END
This is my Code in the form to check the database has inputs, if it doesn't it creates a blank input. However If there is values in the database then it will echo it out
$vId = $_GET['i']; //this is the users unique ID that is send in the query string for testing purpose
if (mysqli_num_rows($rs_username) == 0 )
echo '<input type="text" name="currentusername[]" class="currentusername" placeholder="Current Bikes" >';
else
while ($rs_bike_rows = mysqli_fetch_assoc($rs_bikes))
echo '<input type="text" name="currentusername[]" class="currentusername" value="' . $row['currentusername'] . '">';
echo '<input type="hidden" name="userid[]" value="' . $row['userid'] . '">';
echo '<button type="button" onclick="return deleteFromDbBike('. $rs_bike_rows['oid'] .', '. $vId .');">Delete</button>';
This is to sanitize the inputs that the users inputs in a process file
if (isset($_POST['currentusername']) && $_POST['currentusername'] !== '')
$currentusername = $_POST['currentusername'];
$allusername = '';
foreach ($vcurrentbike as $users)
$allusername .= $users. ' ';
if (filter_var($allusername , FILTER_SANITIZE_STRING) === null)
$vValidation++;
else
$currentusername= '';
later on in the process file to then check the input value and update/insert it
$user = $_POST['userid'];
if ($currentusername != '')
for ($i = 0; $i < count($user); $i++)
$userid = $bike[$i];
$valueuser = $currentusername[$i];
$sqlcheck = "Select `inf_id` FROM usertable WHERE inf_id = $vId";
$resultcheck = mysqli_query($conn,$sqlcheck);
if (mysqli_num_rows($resultcheck) >= 1)
$stmt = $conn->prepare("UPDATE usertable SET currentusername = ? WHERE inf_id = ? and userid = ?");
$stmt->bind_param("sii", $currentperson, $infid, $ownedid);
$currentperson = $valueuser ;
$infid = $vid;
$ownedid = $userid;
$stmt->execute();
//the update code works (tried and tested) just using
//exit to see where the code goes.
exit('1');
else
//this is where the insert value would be however I can
//never get it to echo 0 when it exits; instead i just get a HTTP 500;
exit('0');
;
else
exit('fails');
In the End I want it to be able to check if the user has inputted values and then depending on if they have or have not then either insert or update it. and if the user hasn't just ignore it. and move onto the next field
Edit
it basically has 2 levels to this statement
Level 1:
1.1) if user input is empty then ignore it completely.
1.2) if user input has a value check it against the database
Level 2:
2.1) if the value exists in database then update the values
2.2) if the values don't exists then insert it into the database.
Error I'm running into is that if the value is not in the database to begin with it will create an empty input field.
Now when a user then adds text to the empty field it wants to update it but it doesn't exists. so through out errors at me as there is nothing to update
The States of the input field can be :
1) empty with no value at all
2) Has a value now added so it is not in the db
3) has a value from initial submission of form that is in db
EDIT 2: add more button
<button type="button" onclick="addMoreRows('user')"> Add More Current Usernames</button>
<div id="currentuser"></div>
var itemTypes =
user:
maxLimit: 4,
currentCount: 1,
selector: '#currentuser',
newElement: '<div class="moreusersadd"><input type="text" name="currentusernameadd[]" class="currentusernameadd" placeholder="Current Bikes" ><button class="delete" onclick="deleteRow(this, 'user')">Delete</button></div>'
function addMoreRows(type)
var item = itemTypes[type];
if (item.currentCount < item.maxLimit)
item.currentCount++;
$(item.selector).append(item.newElement);
else
alert('You Have Reached the limits')
function deleteRow(event, type)
$(event).parent('div').remove();
itemTypes[type].currentCount--;
;
php mysqli sql-update
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@w3shivers I have doneSQL COUNT(*)before and that also does not work
– Meitie
Mar 28 at 10:14
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16
add a comment
|
I am trying to build a way to do an input field update check that looks to see if a user input field is empty or not. And then depending on answer if it is empty or not do more checks. So for example if the input field is empty I want it to be ignored so rest of code runs, And if there is a value inside of the input field some more checks will be done to check if it is inside the database or not, and if it is not inside the database then it must be inserted into the database, and if it is already in then just update that field.
The table is a relational one to a main table where inf_id is the main table and userid is the relational one i am working in
So I have tried to do it in different way however I keep running into problems and each time I make a mistake or something that doesn't work I get a HTTP 500 error page saying it can't be reached. I have also tried to do a change the name in the input to other things to see if that effects and different layouts or such neither works I feel like it is something small that I am missing out on
also tired but i may have done it incorrectly since I never really used this before
IF EXISTS (SELECT count(*) FROM `table` WHERE inf_id = $infid)
BEGIN UPDATE GOES HERE END ELSE BEGIN INSERT GOES HERE END
This is my Code in the form to check the database has inputs, if it doesn't it creates a blank input. However If there is values in the database then it will echo it out
$vId = $_GET['i']; //this is the users unique ID that is send in the query string for testing purpose
if (mysqli_num_rows($rs_username) == 0 )
echo '<input type="text" name="currentusername[]" class="currentusername" placeholder="Current Bikes" >';
else
while ($rs_bike_rows = mysqli_fetch_assoc($rs_bikes))
echo '<input type="text" name="currentusername[]" class="currentusername" value="' . $row['currentusername'] . '">';
echo '<input type="hidden" name="userid[]" value="' . $row['userid'] . '">';
echo '<button type="button" onclick="return deleteFromDbBike('. $rs_bike_rows['oid'] .', '. $vId .');">Delete</button>';
This is to sanitize the inputs that the users inputs in a process file
if (isset($_POST['currentusername']) && $_POST['currentusername'] !== '')
$currentusername = $_POST['currentusername'];
$allusername = '';
foreach ($vcurrentbike as $users)
$allusername .= $users. ' ';
if (filter_var($allusername , FILTER_SANITIZE_STRING) === null)
$vValidation++;
else
$currentusername= '';
later on in the process file to then check the input value and update/insert it
$user = $_POST['userid'];
if ($currentusername != '')
for ($i = 0; $i < count($user); $i++)
$userid = $bike[$i];
$valueuser = $currentusername[$i];
$sqlcheck = "Select `inf_id` FROM usertable WHERE inf_id = $vId";
$resultcheck = mysqli_query($conn,$sqlcheck);
if (mysqli_num_rows($resultcheck) >= 1)
$stmt = $conn->prepare("UPDATE usertable SET currentusername = ? WHERE inf_id = ? and userid = ?");
$stmt->bind_param("sii", $currentperson, $infid, $ownedid);
$currentperson = $valueuser ;
$infid = $vid;
$ownedid = $userid;
$stmt->execute();
//the update code works (tried and tested) just using
//exit to see where the code goes.
exit('1');
else
//this is where the insert value would be however I can
//never get it to echo 0 when it exits; instead i just get a HTTP 500;
exit('0');
;
else
exit('fails');
In the End I want it to be able to check if the user has inputted values and then depending on if they have or have not then either insert or update it. and if the user hasn't just ignore it. and move onto the next field
Edit
it basically has 2 levels to this statement
Level 1:
1.1) if user input is empty then ignore it completely.
1.2) if user input has a value check it against the database
Level 2:
2.1) if the value exists in database then update the values
2.2) if the values don't exists then insert it into the database.
Error I'm running into is that if the value is not in the database to begin with it will create an empty input field.
Now when a user then adds text to the empty field it wants to update it but it doesn't exists. so through out errors at me as there is nothing to update
The States of the input field can be :
1) empty with no value at all
2) Has a value now added so it is not in the db
3) has a value from initial submission of form that is in db
EDIT 2: add more button
<button type="button" onclick="addMoreRows('user')"> Add More Current Usernames</button>
<div id="currentuser"></div>
var itemTypes =
user:
maxLimit: 4,
currentCount: 1,
selector: '#currentuser',
newElement: '<div class="moreusersadd"><input type="text" name="currentusernameadd[]" class="currentusernameadd" placeholder="Current Bikes" ><button class="delete" onclick="deleteRow(this, 'user')">Delete</button></div>'
function addMoreRows(type)
var item = itemTypes[type];
if (item.currentCount < item.maxLimit)
item.currentCount++;
$(item.selector).append(item.newElement);
else
alert('You Have Reached the limits')
function deleteRow(event, type)
$(event).parent('div').remove();
itemTypes[type].currentCount--;
;
php mysqli sql-update
I am trying to build a way to do an input field update check that looks to see if a user input field is empty or not. And then depending on answer if it is empty or not do more checks. So for example if the input field is empty I want it to be ignored so rest of code runs, And if there is a value inside of the input field some more checks will be done to check if it is inside the database or not, and if it is not inside the database then it must be inserted into the database, and if it is already in then just update that field.
The table is a relational one to a main table where inf_id is the main table and userid is the relational one i am working in
So I have tried to do it in different way however I keep running into problems and each time I make a mistake or something that doesn't work I get a HTTP 500 error page saying it can't be reached. I have also tried to do a change the name in the input to other things to see if that effects and different layouts or such neither works I feel like it is something small that I am missing out on
also tired but i may have done it incorrectly since I never really used this before
IF EXISTS (SELECT count(*) FROM `table` WHERE inf_id = $infid)
BEGIN UPDATE GOES HERE END ELSE BEGIN INSERT GOES HERE END
This is my Code in the form to check the database has inputs, if it doesn't it creates a blank input. However If there is values in the database then it will echo it out
$vId = $_GET['i']; //this is the users unique ID that is send in the query string for testing purpose
if (mysqli_num_rows($rs_username) == 0 )
echo '<input type="text" name="currentusername[]" class="currentusername" placeholder="Current Bikes" >';
else
while ($rs_bike_rows = mysqli_fetch_assoc($rs_bikes))
echo '<input type="text" name="currentusername[]" class="currentusername" value="' . $row['currentusername'] . '">';
echo '<input type="hidden" name="userid[]" value="' . $row['userid'] . '">';
echo '<button type="button" onclick="return deleteFromDbBike('. $rs_bike_rows['oid'] .', '. $vId .');">Delete</button>';
This is to sanitize the inputs that the users inputs in a process file
if (isset($_POST['currentusername']) && $_POST['currentusername'] !== '')
$currentusername = $_POST['currentusername'];
$allusername = '';
foreach ($vcurrentbike as $users)
$allusername .= $users. ' ';
if (filter_var($allusername , FILTER_SANITIZE_STRING) === null)
$vValidation++;
else
$currentusername= '';
later on in the process file to then check the input value and update/insert it
$user = $_POST['userid'];
if ($currentusername != '')
for ($i = 0; $i < count($user); $i++)
$userid = $bike[$i];
$valueuser = $currentusername[$i];
$sqlcheck = "Select `inf_id` FROM usertable WHERE inf_id = $vId";
$resultcheck = mysqli_query($conn,$sqlcheck);
if (mysqli_num_rows($resultcheck) >= 1)
$stmt = $conn->prepare("UPDATE usertable SET currentusername = ? WHERE inf_id = ? and userid = ?");
$stmt->bind_param("sii", $currentperson, $infid, $ownedid);
$currentperson = $valueuser ;
$infid = $vid;
$ownedid = $userid;
$stmt->execute();
//the update code works (tried and tested) just using
//exit to see where the code goes.
exit('1');
else
//this is where the insert value would be however I can
//never get it to echo 0 when it exits; instead i just get a HTTP 500;
exit('0');
;
else
exit('fails');
In the End I want it to be able to check if the user has inputted values and then depending on if they have or have not then either insert or update it. and if the user hasn't just ignore it. and move onto the next field
Edit
it basically has 2 levels to this statement
Level 1:
1.1) if user input is empty then ignore it completely.
1.2) if user input has a value check it against the database
Level 2:
2.1) if the value exists in database then update the values
2.2) if the values don't exists then insert it into the database.
Error I'm running into is that if the value is not in the database to begin with it will create an empty input field.
Now when a user then adds text to the empty field it wants to update it but it doesn't exists. so through out errors at me as there is nothing to update
The States of the input field can be :
1) empty with no value at all
2) Has a value now added so it is not in the db
3) has a value from initial submission of form that is in db
EDIT 2: add more button
<button type="button" onclick="addMoreRows('user')"> Add More Current Usernames</button>
<div id="currentuser"></div>
var itemTypes =
user:
maxLimit: 4,
currentCount: 1,
selector: '#currentuser',
newElement: '<div class="moreusersadd"><input type="text" name="currentusernameadd[]" class="currentusernameadd" placeholder="Current Bikes" ><button class="delete" onclick="deleteRow(this, 'user')">Delete</button></div>'
function addMoreRows(type)
var item = itemTypes[type];
if (item.currentCount < item.maxLimit)
item.currentCount++;
$(item.selector).append(item.newElement);
else
alert('You Have Reached the limits')
function deleteRow(event, type)
$(event).parent('div').remove();
itemTypes[type].currentCount--;
;
php mysqli sql-update
php mysqli sql-update
edited Mar 28 at 11:51
Meitie
asked Mar 28 at 9:42
MeitieMeitie
451 silver badge8 bronze badges
451 silver badge8 bronze badges
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@w3shivers I have doneSQL COUNT(*)before and that also does not work
– Meitie
Mar 28 at 10:14
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16
add a comment
|
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@w3shivers I have doneSQL COUNT(*)before and that also does not work
– Meitie
Mar 28 at 10:14
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@w3shivers I have done
SQL COUNT(*) before and that also does not work– Meitie
Mar 28 at 10:14
@w3shivers I have done
SQL COUNT(*) before and that also does not work– Meitie
Mar 28 at 10:14
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16
add a comment
|
1 Answer
1
active
oldest
votes
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_POST['username']) && isset($_POST['password']))
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
?>
//-----EDIT-----//
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
if(isset($_POST['no_of_inputs']))
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++)
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_SESSION['new_number']))
for($i=1; $i<=$_SESSION['new_number']; $i++)
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!=""))
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394399%2fhow-to-do-a-database-check-and-depending-on-results-either-update-or-insert-kee%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_POST['username']) && isset($_POST['password']))
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
?>
//-----EDIT-----//
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
if(isset($_POST['no_of_inputs']))
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++)
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_SESSION['new_number']))
for($i=1; $i<=$_SESSION['new_number']; $i++)
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!=""))
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
add a comment
|
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_POST['username']) && isset($_POST['password']))
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
?>
//-----EDIT-----//
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
if(isset($_POST['no_of_inputs']))
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++)
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_SESSION['new_number']))
for($i=1; $i<=$_SESSION['new_number']; $i++)
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!=""))
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
add a comment
|
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_POST['username']) && isset($_POST['password']))
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
?>
//-----EDIT-----//
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
if(isset($_POST['no_of_inputs']))
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++)
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_SESSION['new_number']))
for($i=1; $i<=$_SESSION['new_number']; $i++)
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!=""))
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();
I think this is kind of what you want.
I used my own users table as an example but you should be able to just change the queries to your own tables and columns.
If you have any issue with it just show us your full table structure and I can update it.
<?php
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
echo "<tr>";
echo "<td><input type='text' name='username' placeholder='Username'></td>";
echo "<td><input type='text' name='password' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_POST['username']) && isset($_POST['password']))
$username = $_POST['username'];
$password = $_POST['password'];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
?>
//-----EDIT-----//
So this now has the added header to refresh the page and update the table after each submit.
I also added a check to make sure the new fields weren't blank so it wasn't adding an empty row. And you can now also add as many input rows as you want.
<?php
session_start();
include_once("web/connection.php");
echo "<form method='POST' action='test.php'>";
echo "<table>";
$sql = "SELECT * FROM users";
$stmt = DB::run($sql);
$count = $stmt->rowCount();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$id = $row['id'];
$username = $row['username'];
$password = $row['password'];
echo "<tr>";
echo "<td><input type='text' name='username_".$id."' value='".$username."'></td>";
echo "<td><input type='text' name='password_".$id."' value='".$password."'></td>";
echo "</tr>";
if(isset($_POST['no_of_inputs']))
$_SESSION['new_number'] = $_POST['no_of_inputs'];
for($i=1; $i<=$_SESSION['new_number']; $i++)
echo "<tr>";
echo "<td><input type='text' name='new_username_".$i."' placeholder='Username'></td>";
echo "<td><input type='text' name='new_password_".$i."' placeholder='Password'></td>";
echo "</tr>";
echo "<tr><td colspan='2'><input type='submit'></td></tr>";
echo "</table>";
echo "</form>";
echo "<form method='POST' action='test.php'>";
echo "Add <input type='number' name='no_of_inputs' onchange='this.form.submit()'> rows";
echo "</form>";
for($i=1; $i<=$count; $i++)
if(isset($_POST['username_'.$i]) && isset($_POST['password_'.$i]))
$username = $_POST['username_'.$i];
$password = $_POST['password_'.$i];
$params = [$username,$password,$i];
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt = DB::run($sql,$params);
if(isset($_SESSION['new_number']))
for($i=1; $i<=$_SESSION['new_number']; $i++)
if((isset($_POST['new_username_'.$i]) && $_POST['new_username_'.$i]!="") && (isset($_POST['new_password_'.$i]) && $_POST['new_password_'.$i]!=""))
$username = $_POST['new_username_'.$i];
$password = $_POST['new_password_'.$i];
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
header('location: test.php');
unset($_SESSION['new_number']);
?>
This works and is tested but if you want the basic table structure is:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
In regards to the connection you can change the queries from how I did them like so:
Instead of:
$params = [$username,$password];
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt = DB::run($sql,$params);
You could do something like this:
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$stmt->bind_param($username,$password);
$stmt->execute();
edited Mar 28 at 13:52
answered Mar 28 at 10:16
Paddy HallihanPaddy Hallihan
7841 gold badge8 silver badges29 bronze badges
7841 gold badge8 silver badges29 bronze badges
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
add a comment
|
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
Comments are not for extended discussion or debugging sessions; this conversation has been moved to chat. Please make sure that the answer has been edited to incorporate all relevant information.
– Cody Gray♦
Mar 29 at 0:36
add a comment
|
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55394399%2fhow-to-do-a-database-check-and-depending-on-results-either-update-or-insert-kee%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
This isn't very clear, am i right in saying you want to create an input for each row in your table so that you can update existing ones and then have an extra input to add extras?
– Paddy Hallihan
Mar 28 at 9:51
mysqli_num_rows is checking the $resultcheck which is an array of the results from the DB. Thus you either need to rather count the array total and check if empty and not the mysqli_num_rows. Or add what is currently in the mysqli_query, into the mysql_num_rows. Or do a SQL COUNT(*) all as your select, which will return you the rows count.
– w3shivers
Mar 28 at 9:51
@PaddyHallihan yea so if the theres isnt anything in DB and user puts in an input then i want it to be created but if there is already a value in the database then i want it to be updated
– Meitie
Mar 28 at 10:13
@w3shivers I have done
SQL COUNT(*)before and that also does not work– Meitie
Mar 28 at 10:14
@PaddyHallihan I want it to look at the input. And if there is no value then ignore the input and continue with code. however if there is a value i want it to check if it is in the Database, if it is then update that value if there is not a value then insert it into the database. does that help you?
– Meitie
Mar 28 at 10:16