putting input in a database using mysqli - php
I'm trying to use mysqli to insert data from a form into a database. However I'm not getting it to work :/
This is my code from the page you get to after you filled in the form. The form is not the problem because the variables $headin $author and $thecontent all have data in them. And in the real code database username password and name have real values :)
<html>
<head>
<title>Send!</title>
</head>
<body>
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
# $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}
$author = $_POST['author'];
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];
$query = 'INSERT INTO articles ('heading', 'author', 'content')
VALUES ('$heading','$author','$thecontent')';
$result = $db->query($query);
if ($result) {
echo $db->affected_rows."This was added.";
}
else {
echo "somethings gone very wrong.";
}
$db->close();
?>
</body>
</html>
You cannot add single quotes ' on row names and you have to add double quotes for INSERT:
$query = "INSERT INTO articles (`heading`, `author`, `content`)
VALUES ('$heading','$author','$thecontent')";
Also escape your strings:
$author = $db->real_escape_string($_POST['author']);
$heading = $db->real_escape_string($_POST['heading']);
$thecontent = $db->real_escape_string($_POST['thecontent']);
Related
PHP MySQL DELETE row from html table with link button
I've been looking at this for some time now, all I'm doing is learning PHP with mysql, with no previous programming experience before these so please be kind. I need to delete an entire row from a table. The table is inside list.php and there's a delete button that redirects to delete.php. But all it does it redirects me to a blank page with an url something like "delete.php?id=4" depending on row ID, which seems to be correct. This is connect.php: <?php $server = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "school"; $db_conn = mysqli_connect($server, $db_user, $db_pass, $db_name); $connect_error = 'Sorry, we are experiencing connection problems'; mysql_connect('localhost', 'root', '') or die($connect_error); mysql_select_db('school') or die($connect_error); ?> And this is delete.php : <?php if(isset($_GET['ID'])){ $courseID = $_GET['ID']; $sql_delete = "DELETE FROM Courses WHERE ID = $courseID"; print ($sql_delete); $result = mysqli_query($db_conn,$sql_delete); if($result) { echo "Congratulations. You have deleted this course succesfully."; header('location:list.php'); } else { echo "Error"; error_reporting(E_ALL ^ E_DEPRECATED); } } ?> Notice "print ($sql_delete);", which doesn't print anything either. All I can think of is there is something wrong with the way I am asking for the ID by using $_GET, but can't get my head around it. When I run "DELETE FROM Courses WHERE ID = 4;" inside xampp's mysql module, it works. Uhm... oh well. OK, let me add: This is actually my delete button inside list.php, which gives me an URL based on table row number, based on Course id. <?php echo "<td>Delete";?>
connect.php $server = "localhost"; $db_user = "root"; $db_pass = ""; $db_name = "school"; $db_conn = mysqli_connect($server, $db_user, $db_pass, $db_name); delete.php if(isset($_GET['ID'])){ $courseID = $_GET['ID']; $sql_delete = "DELETE FROM Courses WHERE ID = $courseID"; $result = mysqli_query($db_conn,$sql_delete); if(mysqli_affected_rows($db_conn)>0) { header('location:list.php?result=success'); } else { header('location:list.php?result=fail'); } } list.php (Where is delete button) <?php if(isset($_GET['result')) { if($_GET['result']=='success') { echo "Congratulations. You have deleted this course succesfully."; } else{ echo "error"; } } ?> (Delete button) <a href="delete.php?ID=5" >Delete</a>
Trying to print data from my MYSQL database, doesn't show anything nor any errors
I am trying the fetch the data from my database sunypub from the table journal. Out of many attributes, I am trying to get three atrributes which are of my use on the webpage through PHP, but it is not showing anything on the webpage. This is the option which is directing to the page display.php, which will show me the attributes value of attribute jname, date and location from the table journal <div align = "left"> <form action = "display.php"> <input type = "submit" value = "Show all the Conference List"> </form> </div> display.php: <? php // Create Local variable $taken = "false"; $database = "sunypub"; $password = ""; $username = "root"; // Connect to database $con = mysql_connect('localhost', $username, $password, $database) or die ("Unable to connect"); #mysql_select_db($database) or die("Database not found"); echo "Database Connected"; $query = "select * from journal "; $result = mysql_query($con,$query) or die("Strange Error"); echo "Database Connected"; while( $row = mysql_fetch_assoc( $result, MYSQL_ASSOC ) ){ echo $row['jname']; echo $row['date']; echo $row['location']; echo "Database Connected"; } mysql_close($con); ?>
mysql_* is deprecated and is removed in new PHP version. So I highly recommend you to change to PDO or mysqli_* prepared statements, instead of fixing your old code. So your code could look something like this: (Note that you have to remove the space here: <? php) <?php // Create Local variable $taken = "false"; $dbhost = "localhost"; $dbname = "sunypub"; $dbpass = ""; $dbuser = "root"; try { $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "SELECT * FROM journal"; foreach($dbh->query($sql) as $row) { echo $row['jname']; echo $row['date']; echo $row['location']; echo "Database Connected"; } $dbh = NULL; } catch(PDOException $e) { echo $e->getMessage(); } ?>
XML request MySQL by PHP
Actually i'm working in a flash web page using XML. I want to make a sing up page with XML that uses PHP to insert data into de MySQL database, but I'm stuck... and i my XML-PHP knowledge are not enough for this duty. This is the XML file: <?xml version="1.0" encoding="utf-8"?> <data> <title>Sing up</title> <request field1="user" field2="email" field3="password" field4="other">reg.php</request> <description><![CDATA[Please sing up!]]></description> </data> The reg PHP file: <?php function Reg() { if (isset($_POST['reg'])==true) { require_once('db_conf.php'); $user = $_POST['username']; $pass = sha1(strtoupper($user.':'.$_POST['password'])); $email = $_POST['email']; $con = mysql_connect($dbhost, $dbuser, $dbpassword); if (!$con) { die('Could not connect!'); } else { mysql_select_db("$logondb", $con); $sql="INSERT INTO accounts (username, sha_pass_hash, email) VALUES ('$user','$pass','$email')"; if (!mysql_query($sql,$con)) { die('Error creating account.'); } echo $succesmsg; mysql_close($con); } } else { ?> And PHP conf for database: <?php $dbhost = 'localhost'; $dbuser = 'user'; $dbpassword = 'password'; // Accounts Database $logondb = 'accounts'; $errormsg="Error creating account.."; $succesmsg="Account created!"; ?>
I would like to suggest using PDO instead - it's a more general approach. And then you should use data-binding to reduce vulnerability against SQL Injections... This should take you one step further: <?php function Reg() { if (isset($_POST['reg'])==true) { require_once('./db_conf.php'); $user = $_POST['username']; $pass = sha1(strtoupper($user.':'.$_POST['password'])); $email = $_POST['email']; $dsn = "mysql:host=$dbhost;dbname=$logondb"; $pdo = new PDO($dsn,$dbuser,$dbpassword); if (!$pdo) { die('Could not connect!'); } else { $sql = "INSERT INTO accounts (username, sha_pass_hash,email) VALUES (:user,:pass,:email)"; $stmt = $pdo->prepare($sql); $res = $stmt->execute(array("user"=>$user , "pass"=>$pass , "email" => $email)); if (!$res) { echo "Error :((<pre>"; var_dump($stmt->errorInfo()); echo "</pre>"; } else { echo $succesmsg; } } } else { echo "reg was not set - terminating...!"; } } Reg(); // execute it! ?>
How do I insert into a form with over 100 fields
I've created a user form in which once the submit button is pressed I would like to send/insert the data to mysql database adding a new record. The form has over 100 input fields. How can I accomplish this. Here is my sample php code. <html> <head> </head> <body> <?php if (isset($_POST['submit'])){ //Variables for connecting to your database. //These variable values come from your hosting account. $hostname = "hostname"; $username = "username"; $password = "password"; $dbname = "dbname"; $mystuff = "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state"; $con = mysql_connect("$hostname","$username","$password"); if (!$con){ die ("Can not connect:" . mysql_error()); } mysql_select_db("dbname",$con); $sql = "INSERT INTO dbname ($mystuff) VALUES ('$_POST[$mystuff]')"; mysql_query($sql,$con); mysql_close($con); } ?> </body> </html>
$mystuff should be an array. You can generate your query and form with an loop. Do validation if these is for productive use! $_POST is also an array, so $_POST["field1", "field2", ...] ist an syntax error. You can only access one key at once e.g. $_POST['field1'] . ',' . $_POST['field2'] You can join all values in an array by an char (e.g. ',') with implode() rethink your Database schema! untested: <html> `enter code here`<head> `enter code here`</head> <body> <?php >if (isset($_POST['submit'])){ //Variables for connecting to your database. //These variable values come from your hosting account. $hostname = "hostname"; $username = "username"; $password = "password"; $dbname = "dbname"; $mystuff = array( "tenant_lname","tenant_fname","tenant_mname","ssn","dl_number","dl_state","birthday","tenant_hphone","tenant_wphone","tenant_cphone","curr_street","curr__unit","curr_city","curr_state","curr_zip","how_long_from","how_long_to","last_rent_mnt","last_rent_amt","own_man_name","own_man_tel","curr_reason","pre_street","pre_unit","pre_city","pre_state","pre_zip","pre_from","pre_to","pre_last_rent","pre_amt","pre_owner","pre_owner_tel","pre_reason","sec_pre_street","sec_pre_unit","sec_pre_city","sec_pre_state","sec_pre_zip","sec_pre_from","sec_pre_to","sec_pre_last_paid_mnt","sec_pre_amt","sec_pre_owner","sec_pre_owner_tel","sec_pre_reason","curr_emp_name","curr_emp_add","curr_emp_phone","curr_emp_pos","curr_emp_bus_type","curr_emp_sup","curr_emp_from","curr_emp_to","curr_emp_salary","pre_emp_name","pre_emp_add","pre_emp_phone","pre_emp_pos","pre_emp_bus_type","pre_emp_sup_name","pre_emp_from","pre_emp_to","pre_emp_salary","move_date","addntl_occ_name","addntl_occ_age","addntl_occ_relation","addntl_ft","addntl_pt","addntl_occ1_name","addntl_occ1_age","addntl_occ1_relation","addntl_occ1_ft","addntl_occ1_pt","addntl_occ2_name","addntl_occ2_age","addnt2_occ1_relation","addntl_occ2_ft","addntl_occ2_pt","addntl_occ3_name","addntl_occ3_age","addntl_occ3_relation","addntl_occ3_ft","addntl_occ3_pt","credit_yes","credit_no","det_yes","det_no","evict_yes","evict_no","bnkry_yes","bnkry_no","fel_yes","fel_no","pet_yes","pet_no","pet_numb","pet_type","furn_yes","furn_no","ins_cov_yes","ins_cov_no","ints_yes","ints_no","ints_type","smoke_yes","smoke_no","occ_smoke_yes","occ_smoke_no","explain_smoke","bnk_name","bnk_add","checking","checking_bal","saving","saving_bal","bnk_name1","bnk_add1","checking1","checking_bal1","saving1","saving_bal1","other_income","credit_name","credit_add","credit_city","credit_acct","credit_bal","credit_payment","credit_name1","credit_add1","credit_city1","credit_acct1","credit_bal1","credit_payment1","credit_acct2_name","credit_add2","credit_city2","credit_acc2","credit_bal2","credit_payment2","credit_acc3_name","credit_acc3_add","credit_acc3_city","credit_acc3_number","credit_acc3_bal","credit_acc3_payment","emer_contact_name","emer_contact_add","emer_relation","emer_phone","reg_owner_yes","reg_owner_no","reg_who","vehicle_year","vehicle_make","vehicle_model","vehicle_color","vehicle_license","veh_state","vehicle2_year","vehicle2_make","vehicle2_model","vehicle2_color","vehicle2_license","veh2_state"); $sql_values=array(); foreach($mystuff as $fieldname) { /* do validation! */ $sql_values[$fieldname] = "'" . mysql_real_excape_stiring($_POST[$fieldname]) . "'"; } $con = mysql_connect("$hostname","$username","$password"); if (!$con){ die ("Can not connect:" . mysql_error()); } mysql_select_db("dbname",$con); $sql = "INSERT INTO dbname (".implode(',', $mystuff).") VALUES (" . implode(',', $sql_values) . ")"; mysql_query($sql,$con); mysql_close($con); } foreach($mystuff as $fieldname) { echo "...an input field..."; } ?> </body>
Create inputs something like : <input type="text" name="datas[firstname]"/> <input type="text" name="datas[lastname]"/> You can process the data using : <?php $datas = $_POST['datas']; $columns = implode(",",array_keys($datas)); //add ' since mysql use ' for strings $values = implode("','",$datas); $sql = "INSERT INTO dbname (".$columns.") VALUES ('".$values."')"; Hope this help.
Comparing database stringvalue with new stringvalue
Here is what I'm trying to do: When user adds a contact to his list, the number of this contact gets run by with the numbers in the database and it gives feedback if the user is already in the database or not. Right now I always get back "User is in database" even though he isn't. Then again I'm not that well acquainted with php. I changed the code a bit again, now it doesn't work at all, because it doesn't like the part $number = ($_GET["number"] from $DB_Table); Full code <?php $DB_HostName = "localhost"; $DB_Name = "db"; $DB_User = "user"; $DB_Pass = "pw"; $DB_Table = "contacts"; $number = ($_GET["number"] from $DB_Table); $fnumber = ($_GET["fnumber"]); if ($number == $fnumber) { echo "This user is already in database"; } else { echo "This user isn't in the database"; } $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error()); mysql_select_db($DB_Name,$con) or die(mysql_error()); mysql_close($con); ?>
I don't actually see you executing the database query. You could do something like this: <?php $DB_HostName = "localhost"; $DB_Name = "db"; $DB_User = "user"; $DB_Pass = "pw"; $DB_Table = "contacts"; $con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error()); mysql_select_db($DB_Name,$con) or die(mysql_error()); $fnumber = mysql_real_escape_string($_GET["fnumber"]); $result = mysql_query("SELECT * FROM $DB_Table WHERE Something = '$fnumber'", $con); if ($result) { // Check the number of rows in the result set if (mysql_num_rows($result) > 0) { echo "This user is already in database"; } else echo "This user isn't in the database"; } mysql_close($con); ?>
This is not valid PHP code: $number = ($_GET["number"] from $DB_Table); $_GET["number"] represents the value of the "number" parameter that you find in the url of your page. Example: http://example.com/index.php?number=7 so $_GET["number"] is 7. In your code, $DB_Table is a just a string ("contact") and "from" does not fit there using php syntax. mysql_select_db($DB_Name,$con) or die(mysql_error()); is valid PHP but you are not doing anything with what you get from the database. I suggest you at least take a look at this tutorial php mysql select