I have a problem with "ADD" and "INSERT" functions in database - php

I wanna ask you, how can I fix this code? I have a problem with "ADD" and "INSERT" functions in database. I can only delete from database, but "add and insert" functions do nothing.
this is my about.php file.
$mode = 'add';
$about = '';
if(isset($_GET['edit']) && is_numeric($_GET['edit'])){
$sql = "SELECT * FROM `about_me` WHERE `about_me`.`id` =".$_GET['edit'];
$result_about = mysqli_query($conn, $sql);
if(mysqli_num_rows($result_about) == 1) {
$mode = 'edit';
$about = mysqli_fetch_assoc($result_about);
}
}
$apie = '';
if(isset($_POST["submit"])){
if(isset($_POST["apie"])){
$apie = trim($_POST["apie"]);
}
}
elseif($mode=='edit') {
$apie = $about['about'];
}
if($mode=='add') {
if(($apie!='')){
$sql = 'INSERT INTO about_me(about)
VALUES ("'.$apie.'")';
mysqli_query($conn, $sql);
header('Location:about.php');
die();
}
}
elseif($mode=='edit') {
if(($apie!='')){
$sql = "UPDATE `about_me` SET `about` = '".$apie."' WHERE `about_me`.`id` = ".$_GET['edit'];
mysqli_query($conn, $sql) ;
}
}
<..>
<input type = "text" name = "apie" value = "<?php echo $apie; ?>">
<br><br>
<input type = "submit" name = "submit" value = "Gerai">
<br><br>
I checked mysql error, with https://www.w3schools.com/php/func_mysqli_error.asp, and then it insert in my DB. I think there is code foult, but I don't know where.

You have a slight error with your first query, you can't use parentheses next to the database selector, I'd recommend creating a separate file with a database connection that you can refer to as $conn, your first query should look like this:
$sql = "INSERT INTO about_me
VALUES (?)";
Also, you should look into prepared statements for your queries, instead of inserting them directly you use a question mark? to which you bind the parameter/parameters. This helps prevent SQL injections!
Hope this helps!:)

Related

how to insert multiple row data into multiple row in php mysql

I have retrieved data from the table and all the retrieved data to be stored in another table in each row. I have tried the below code but it is inserting only "
$roll_no = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$section = $_POST['section'];
$m_am = $_POST['m_am'];
$a_pm = $_POST['a_pm'];
$date = $_POST['date'];
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
/*$sql_2 = mysql_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`,
?>"
Use mysqli instead of mysql to prevent hacking
and also validate the user input use htmlentities() or htmlspecialchars()
<?php
$roll_no = htmlspecialchars($_POST['roll_no']);
$name = htmlspecialchars($_POST['name']);
$class = htmlspecialchars($_POST['class']);
$section = htmlspecialchars($_POST['section']);
$m_am = htmlspecialchars($_POST['m_am']);
$a_pm = htmlspecialchars($_POST['a_pm']);
$date = htmlspecialchars($_POST['date']);
echo $a_pm .'<br>'.$m_am.'<br>'.$roll_no;
$sql_2 = mysqli_query("INSERT INTO stud_class_attendance (`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`, `date`)
values ('$roll_no','$name','$class','$section','$m_am','$a_pm','$date');
$sql_2->execute();
?>
You need a loop for that..
Execute your first query. get all the records from the first query. iterate them and insert one by one in database
See the example
$select = mysql_query("SELECT
name,rollno,class,section,a_am,a_pm,`date`
FROM `student`");
// check if event 1 row exists in database
if(mysql_num_rows($select) > 0 ){
// while loop to iterate every row one by one
$count =0;
while ($row = mysql_fetch_assoc($select)) {
$insert = mysql_query("INSERT INTO `stud_class_attendance`
(`sca_rollno`, `sca_name`, `sca_class`, `sca_section`,`sca_am`, `sca_pm`)
VALUES
('".$row['rollno']."','".$row['name']."','".$row['class']."',
'".$row['section']."','".$row['a_am']."','".$row['a_pm']."')");
// check if the query was executed
if(mysql_insert_id() > 0){
$count++;
}
}
}
echo $count." rows inserted";
$sql='
INSERT INTO `stud_class_attendance` (
`sca_rollno`, `sca_name`,`sca_class`, `sca_section`,`sca_am`, `sca_pm`
)
SELECT rollno,name,class,section,a_am,a_pm FROM `student`
';
$sql2=mysqli_query($sql);
$sql2->execute();

Insert NULL values on DB (method)

UPDATE----
Afer using this method:
foreach($_POST as $k => $v) {
$params[] = empty($v)? "NULL":$v;
}
$params_string_values = "'" . implode("','",$params) . "'";
$param_name_list = "tu_id,tu_status,tu_name,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s,tu_sun_1_e,tu_sun_2_s,tu_sun_2_e,tu_sun_3_s,tu_sun_3_e";
$param_values = "'','1',{$params_string_values}";
$insert_query = mysql_query("INSERT into turn_conf( {$param_name_list} ) values ({$param_values})");
It creates a valid query as it seems (here I paste it), but no NULL value is stored on databse, all NULL values go to database as "00:00":
INSERT into turn_conf( tu_id,tu_status,tu_name,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,tu_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tue_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s,tu_sun_1_e,tu_sun_2_s,tu_sun_2_e,tu_sun_3_s,tu_sun_3_e ) values ('','1','12345555','1','10:00','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL','NULL')
This is what it records on DB:
I have this query, in which sometimes variables '$va1', '$val2' and '$val3' will have no value:
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1,value2,value3) VALUES ('','$va1','$val2','$val3')") or die (mysql_error());
In case any of these variables have no value stored, anything related to it must be sent to the DB (in order to store a NULL value on DB), for exampe if only '$val1' stores info, the final query must be:
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1) VALUES ('','$va1')") or die (mysql_error());
To solve this I have created an structure for each variable, checking wether it stores something or not, and in case it doesn't, just declarating nothing and sending nothing:
if ($_POST['value1'] == ""){
$val1_p = "";
$val1_s = "";
}else {
$val1_p = ",value1";
$val1_sv = $_POST['value1'];
$val1_s = ", '$val1_sv'" ;}
if ($_POST['value2'] == ""){
$val2_p = "";
$val2_s = "";
}else {
$val2_p = ",value2";
$val2_sv = $_POST['value2'];
$val2_s = ", '$val2_sv'" ;}
if ($_POST['value3'] == ""){
$val3_p = "";
$val3_s = "";
}else {
$val3_p = ",value3";
$val3_sv = $_POST['value3'];
$val3_s = ", '$val3_sv'" ;}
and:
$insert = mysql_query("INSERT INTO turn_conf (tu_id $val1_p $val2_p $val3_p) VALUES ('' $val1_s $val2_s $val3_s)") or die (mysql_error());
This works, and creates the right query, but id like to know if you find ths method proper, or if it would be better to choose another more efficient one. Please not in this example I used only 3 variables, but this query on real has 43 variables, I make this question due to the amount of data.
$insert = mysql_query("INSERT INTO turn_conf (tu_id,value1,value2,value3) VALUES ('','".((isset($va1))?"'".$va1."'":"NULL")."','".((isset($va2))?"'".$va2."'":"NULL")."','".((isset($va3))?"'".$va3."'":"NULL")."')") or die (mysql_error());
Basically you want to test if the value is set. We use the short if-notation for this:
isset($va1)?"'".$va1."'":"NULL"
If $va1 is set (has a value), we will put "'value'" in the query, otherwise "NULL" for an empty value.
If you want to test on an empty string too:
(isset($va1) && $va1 != '')?"'".$va1."'":"NULL"
If you don't use prepared statement Try this:
foreach($_POST as $k => $v) {
$params[] = empty($v)? "NULL":$v;
}
mysql_query("insert into turn_conf(field1,field2...) values(" . implode(",",$params). ");
If you use prepared statement (better!) try something like this:
foreach($_POST as $v) {
$params[] = $v;
}
$sth = $dbh->prepare("INSERT INTO turn_conf (tu_id $val1_p $val2_p $val3_p) VALUES (?,?,?)");
$sth->execute($params);
So simple!
PS: This is an example but doesn't use directly $_POST value, filter it before (http://www.php.net/manual/en/function.filter-input.php, and http://www.php.net/manual/en/filter.filters.sanitize.php). example:
$field_int= filter_input(INPUT_POST, 'field1', FILTER_SANITIZE_NUMBER_INT);
UPDATE
you use this code:
$insert = mysql_query("INSERT into turn_conf(tu_id,tu_name,tu_status,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,t‌​u_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tu‌​e_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_‌​e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu‌​_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat‌​_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s) values('','$newTurnName','1','$newTurnType'," . implode(",",$params). "))")
but change it like this:
$params_string_values = "'" . implode("','",$params) . "'";
$param_name_list = "tu_id,tu_name,tu_status,tu_fk_tt_id,tu_mon_1_s,tu_mon_1_e,tu_mon_2_s,t‌​u_mon_2_e,tu_mon_3_s,tu_mon_3_e,tu_tue_1_s,tu_tue_1_e,tu_tue_2_s,tu_tue_2_e,tu_tu‌​e_3_s,tu_tue_3_e,tu_wed_1_s,tu_wed_1_e,tu_wed_2_s,tu_wed_2_e,tu_wed_3_s,tu_wed_3_‌​e,tu_thu_1_s,tu_thu_1_e,tu_thu_2_s,tu_thu_2_e,tu_thu_3_s,tu_thu_3_e,tu_fri_1_s,tu‌​_fri_1_e,tu_fri_2_s,tu_fri_2_e,tu_fri_3_s,tu_fri_3_e,tu_sat_1_s,tu_sat_1_e,tu_sat‌​_2_s,tu_sat_2_e,tu_sat_3_s,tu_sat_3_e,tu_sun_1_s";
$param_values = "'','{$newTurnName}','1','{$newTurnType}',{$param_string_values}";
$insert_query = mysql_query("INSERT into turn_conf( {$param_name_list} ) values ({$param_values})");

Post not being recieved from checkbox form php

I'm posting from the HTML code shown in this jsfiddle to the PHP page for which the code is below. The issue is that the array $_POST['selectedpost'] isn't being received. That's the array containing which checkboxes were ticked. In the js fiddle I added in an example row to the table containing the checkboxes as normally these are generated using PHP and SQL.
<?php
include "connect2.php";
if (isset($_POST['selectedpost'])) {
$postschecked = $_POST['selectedpost'];
$length = count($postschecked);
}
else{
returnpage();
}
if (isset($_POST['deleteposts'])) {
foreach($postschecked as $post_id){
$sql = "DELETE FROM posts WHERE post_id='$post_id'";
mysql_query($sql);
}
returnpage();
}
if (isset($_POST['passposts'])) {
foreach($postschecked as $post_id){
$sql = "UPDATE posts SET moderation=1 WHERE post_id='$post_id'";
mysql_query($sql);
}
returnpage();
}
if (isset($_POST['editpost'])) {
if ($lenght==1){
foreach($postschecked as $post_id){
header("location:editpost.php?post_id=$post_id");
}
}
else{
returnpage();
}
}
if (isset($_POST['returnpost'])) {
if (isset($_POST['reasonreturned'])) {
foreach($postschecked as $post_id){
$sql = "SELECT description FROM posts WHERE post_id='$post_id'";
$query = mysql_query($sql);
$array = array();
while ($row = mysql_fetch_array($query, MYSQL_NUM)) {
$array[] = $row; }
$description = "".$array[0][0];
$description = $description . "<br/><br/><span style='color:red;font-size:18px;'>" . $_POST['reasonreturned'] . "</span>";
$sql = "UPDATE posts SET description='$description' WHERE post_id='$post_id'";
$query = mysql_query($sql);
}
}
foreach($postschecked as $post_id){
$sql = "UPDATE posts SET moderation=3 WHERE post_id='$post_id'";
$query = mysql_query($sql);
}
returnpage();
}
if ($length){
returnpage();
}
function returnpage(){
//header("location:moderate.php");
}
?>
http://jsfiddle.net/3A6az/2/
Also extra note, I am aware as to how un-efficient my code is in places and I'm also aware to the fact I should drop mysql and move to something like mysqli. Thank's for any help given
If you have more than 1 checkbox you need to use
name='selectedpost[]'
It will then be available to you with $_POST['selectedpost']; as an array.
Hope this helps!
You're using an unbracketed input <input type='checkbox' name='selectedpost' value='404'></input> plus you don't need </input> <(FYI)
If anything you shouldn't be using value='404' unless that's what you want to pass as a "value".
You probably meant to use multiple checkboxes and using name='selectedpost[]'
I.e.:
<input type='checkbox' name='selectedpost[]'>
Using square brackets [] are treated as an array.
Footnotes:
I would like to point out though, that switching to mysqli_* functions would be most beneficial. mysql_* functions are deprecated.
Using mysqli_* functions with prepared statements or PDO would be even better in order to protect yourself from SQL injection.
Here is a guide on how to prevent SQL injection: How can I prevent SQL injection in PHP?
N.B.: I also found a typo which may give you trouble if ($lenght==1){
You have the word $length in your code as well. Change it to if ($length==1){

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