POST empty fields result in query error - php

I have a form with some fields
<form action="add.php" method="post">
/*Some fields*/
</form>
Also I created the following function to quote and escape form submitted values
<?php
// Quote and escape form submitted values
function db_quote($value) {
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>
Then I pass values to the function as following
$inventoryId = db_quote($_POST['inventoryId']);
$sn = db_quote($_POST['sn']);
$model = db_quote($_POST['model']);
//etc...
Every thing work fine if I fill all the fields, but if there is at least one empty filed i.e. no value entered by the user I get the following error
Catchable fatal error: Object of class mysqli could not be converted to string in etc...
Here is the query I am trying to run
<?php
$sql = "INSERT INTO inventory (id,manufacturer_id,supplier_id,servicer_id,operator_id,sn,model,inventory_name,inventory_type,description,power,purchase_order,purchase_cost,arrival_date,installation_date,warranty_date,incident_history,conditions,m_next_date,m_start_date,m_deadline,lifetime,inspection_frequency,location,purchased_from)
VALUES ($inventoryId,$manufacturer,$supplier,$servicesId,$operatorId,$sn,$model,$inventoryName,$inventorType,$description,$power,$purchaseOrder,$purchaseCost,$arrivalDate,$installationDate,$warranty,$incident,$conditions,$nextDate,$startDate,$deadline,$lifetime,$inspection,$location,$purchasedFrom);";
if ($connection->query($sql) === TRUE) {
echo "<p>New inventory ".$inventoryId." created successfully</p>";
} else {
echo "Error: " . $sql . "<br>" . $connection;
}
$connection->close();
?>
Update: The issue only with Auto Increment columns

<?php
// Quote and escape form submitted values
function db_quote($value) {
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>
Convert it to
<?php
// Quote and escape form submitted values
function db_quote($value) {
if(!$value) return '';
$connection = db_connect();//Connection with database "NO ISSUE HERE"
return "'" . mysqli_real_escape_string($connection,$value) . "'";//Maybe the issue here
}
?>

Related

How do I fix this code so that it posts the results of a PHP webcrawler into a MySQL table?

I am fooling around with some pre-written code for a PHP webcrawler. It is designed to read URLs off any specified website and post them to a page. I have been attempting to alter it to instead post the $url to a MySQL database. I feel like I am maybe 90% of the way there, as I am getting a connection to the database and record added. However, the record added is not the URL, but instead just an empty record. The webcrawler code worked in posting URLs to a webpage, but I am having trouble successfully fusing the two goals. Any help is appreciated!
Here is the complete code:
<?php
$host="localhost"; // Host name
$username="lightonl"; // Mysql username
$password="Gracias099"; // Mysql password
$db_name="lightonl_my_db"; // Database name
$tbl_name="instruments"; // Table name
include("simple_html_dom.php");
$crawled_urls=array();
$found_urls=array();
function rel2abs($rel, $base){
if (parse_url($rel, PHP_URL_SCHEME) != ''){
return $rel;
}
if ($rel[0]=='#' || $rel[0]=='?'){
return $base.$rel;
}
extract(parse_url($base));
$path = preg_replace('#/[^/]*$#', '', $path);
if ($rel[0] == '/'){
$path = '';
}
$abs = "$host$path/$rel";
$re = array('#(/.?/)#', '#/(?!..)[^/]+/../#');
for($n=1; $n>0;$abs=preg_replace($re,'/', $abs,-1,$n)){}
$abs=str_replace("../","",$abs);
return $scheme.'://'.$abs;
}
function perfect_url($u,$b){
$bp=parse_url($b);
if(($bp['path']!="/" && $bp['path']!="") || $bp['path']==''){
if($bp['scheme']==""){
$scheme="http";
}else{
$scheme=$bp['scheme'];
}
$b=$scheme."://".$bp['host']."/";
}
if(substr($u,0,2)=="//"){
$u="http:".$u;
}
if(substr($u,0,4)!="http"){
$u=rel2abs($u,$b);
}
return $u;
}
function crawl_site($u){
global $crawled_urls, $found_urls;
$uen=urlencode($u);
if((array_key_exists($uen,$crawled_urls)==0 || $crawled_urls[$uen] < date("YmdHis",strtotime('-25 seconds', time())))){
$html = file_get_html($u);
$crawled_urls[$uen]=date("YmdHis");
foreach($html->find("a") as $li){
$url=perfect_url($li->href,$u);
$enurl=urlencode($url);
if($url!='' && substr($url,0,4)!="mail" && substr($url,0,4)!="java" && array_key_exists($enurl,$found_urls)==0){
$found_urls[$enurl]=1;
echo $url."<br/>";
}
}
}
}
crawl_site("http://www.sfgate.com");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `lightonl_my_db`.`instruments` (`id`, `description`) VALUES (NULL, '$url.');";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
mysqli_close($conn);
?>
Again, I may be totally wrong, but everything seems to be functioning smoothly except that only one record is being added (instead of the multiple URLs returned by the webcrawler), and it's not the URL, but an empty record.
Couple of things to correct.
if your table has auto-increment, there is no need to specify id in insert.
Single dot appears from (NULL, '$url.'). There is a . after $url.
Where from do you get $url variable? It might be that there is no $url variable defined at the moment of insert.
Edited
Your sql should be found in the foreach loop so that each url is added to your db and don't forget to remove the extra ; and the . after $url:
function crawl_site($u){
global $crawled_urls, $found_urls;
$uen=urlencode($u);
if((array_key_exists($uen,$crawled_urls)==0 || $crawled_urls[$uen] < date("YmdHis",strtotime('-25 seconds', time())))){
$html = file_get_html($u);
$crawled_urls[$uen]=date("YmdHis");
foreach($html->find("a") as $li){
$url=perfect_url($li->href,$u);
$enurl=urlencode($url);
if($url!='' && substr($url,0,4)!="mail" && substr($url,0,4)!="java" && array_key_exists($enurl,$found_urls)==0){
$found_urls[$enurl]=1;
$sql = "INSERT INTO `lightonl_my_db`.`instruments` (`id`, `description`) VALUES (NULL, '$url')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo $url."<br/>";
}
}
}
}

Registration Form : No error showing but No data on mysql DATABASE

I am trying to develop a registration form.
When I fill all the filed and submit the form, no error showing
the server is connected but no data on mysql database table. Bellow L attached the action file of form. What do I miss? and how can I solve it?
<?php
$mysqli_servername = "localhost";
$mysqli_username = "admin_try";
$mysqli_password = "rFT5hePS5u";
$mysqli_database = "indepe";
// Create connection
$conn = mysqli_connect($mysqli_servername,$mysqli_username,$mysqli_password,$mysqli_database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'>Back to main page</a>";
if (isset($_GET["submitreg"]))
{
$id= mysqli_real_escape_string($conn, $_POST['id']);
$country = mysqli_real_escape_string($conn, $_POST['country']);
$email = mysqli_real_escape_string($conn,$_POST['email']);
$password = mysqli_real_escape_string($conn,$_POST['password']);
$re_password = mysqli_real_escape_string($conn,$_POST['re_password']);
$compnay = mysqli_real_escape_string($conn,$_POST['compnay']);
$contact = mysqli_real_escape_string($conn,$_POST['contact']);
$tell = mysqli_real_escape_string($conn,$_POST['tell']);
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell);
VALUES('id','$country','$email','$password','$re_password','$compnay','$contact'),'$tell'";
if ($conn->query($sql) === TRUE) {
echo "record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if (mysqli_query($conn, $sql)) {
echo " record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
//$conn->close();
mysqli_close($conn);
?>
There are few errors in your insert query
Remove the semicolen after tell in your insert query
You gave id in values instead of $id
$tell is outside the bracket
$sql = "INSERT INTO registration(id,country,email,password,re_password,compnay,contact,tell) VALUES('$id','$country','$email','$password','$re_password','$compnay','$contact','$tell'");
Im not sure whether that is your problem or it occured your copying your code..because no error was shown
I think you mistake in insert query remove semicolon before VALUES keyword and if id column auto increment then no need to add it in insert query otherwise you need add it properly and ,'$tell' is outside the bracket please make it proper
$sql = "INSERT INTO registration(country,email,password,re_password,compnay,contact,tell) VALUES ('$country','$email','$password','$re_password','$compnay','$contact','$tell')";
I thing you need to add privileges to particular user to insert records. as you have declared $mysqli_username = "admin_try";. now go to localhost/phpmyadmin and then add privileges to particular user!!
You are using $_GET check and for submitting the form which is wrong. It's always recommened to do POST request for form submission.
if (isset($_GET["submitreg"]))
But, later in your code to get the the data you are using $_POST.
$id= mysqli_real_escape_string($conn, $_POST['id']);
Please check your form method in html make it POST and change
if (isset($_GET["submitreg"]))
to
if (isset($_POST["submitreg"]))

Checkbox that updates dynamically

I have a checkbox that dynamically updates a MySQL database when it is checked/unchecked using PHP and Ajax.
I am now trying to pass the users name so that the Ajax script can update the database with the users full name.
I have the name held in a variable called $full_name. I cannot seem to get this working though. Please see the code below:
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function chkit(uid, chk) {
chk=document.getElementById("chk").checked;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: { chkYesNo: chk, record_id: uid, full_name: user},
success:function(data){
// successful request; do something with the div background color
if(data==1)
{
$("#replace").addClass("checked_div_status").removeClass("replace");//removing first class and adding second class
}
else
{
$("#replace").addClass("replace").removeClass("checked_div_status");//removing second class and adding first class
}
}
});
}
</script>
HTML:
<?php
$record_id = $_GET['veh_id'];
include '../dbconnect.php';
//fetching data from database
$select=mysql_fetch_array(mysql_query("select invoice_checked from vehicle_details where veh_id = '$record_id' "));
?>
<!--The checkbox whose enable to change div his background color and onclick call function to update database-->
<table width=“100%”>
<td id="replace2" class="<?php if($select['invoice_checked']==1) { echo 'checked_div_status2'; } else{ echo 'replace2'; } ?>">
<input name="chk2" type="checkbox" id="chk2" value="1" onclick="chkit2(<?php echo $record_id;?>,'chk2');" <?php if($select['invoice_checked']==1) { echo 'checked'; } else{ echo ''; } ?> />
Invoice Checked
</td>
</table>
Ajax.php:
<?php
mysql_connect("server", "username", "password") or die("Could not connect: " . mysql_error());
mysql_select_db("database");
//here $get variable receive checkbox value true(1) either false(0)
$get=$_GET['chkYesNo'];
//here $get_id variable receive value of current id that you passed
$get_id=$_GET['record_id'];
$get_user=$_GET['full_name'];
if($get=="true")
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='1', check_user='".$get_user."' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
else
{
$mysql_query=mysql_query("update vehicle_details set hpi_registered='0', check_user='0' where veh_id='".$get_id."'");
$select=mysql_fetch_array(mysql_query("select hpi_registered from vehicle_details where veh_id='".$get_id."'"));
echo $select['hpi_registered'];
}
?>
Any help would be greatly received.
Thanks,
John
Some debug lession for you. Please, check my comments:
// Do not need to replicate your code, if the same things happens in it.
//instead, use a condition to set your variables, and use these variables later.
if ($get == "true") {
$hpi_registered = 1;
//Escape your variable to avoid sql injection
$checkUser = mysqli_real_escape_string($conn, $_GET["full_name"]);
} else {
$hpi_registered = 0;
$checkUser = 0;
}
//Store your query in a variable, so you can debug / dump it
//Let's dump it, see, what is your query, and try to run in directly in sql.
//Maybe it has syntax error.
$sql = "UPDATE vehicle_details SET"
. " hpi_registered='" . intval($hpi_registered) . "',"
. " check_user='" . $checkUser . "'"
. " WHERE veh_id='" . intval($get_id) . "'";
mysqli_query($conn, $sql);
//What happens, if you run it directly in sql? If this fails, now here is your
//error.
$sql = "SELECT hpi_registered"
. " FROM vehicle_details"
. " WHERE veh_id='" . intval($get_id) . "'";
//Do the same like previous query.
$res = mysqli_query($conn, $sql);
$select = mysqli_fetch_array($res);
echo $select['hpi_registered'];
DO NOT use mysql functions, because they are deprecated. Use mysqli or PDO instead.
Avoid sql injection by escaping your variables.

updating a flag in mysql via radiobutton onclick handler in php

I want to update a column in a table in mysql. Basically the column is the flag for the entries of that db table.
The modification of the column is resetting all values to 0 and setting the desired row to 1, for this reason I have post.php file which looks like
<?php
require_once('class.uuid.php');
$connection = mysql_connect("---logindetailshere---");
$db = mysql_select_db("---dbnamehere---",$connection);
switch($_REQUEST['action']){
case ...
break;
case ...
break;
case 'changeDisp':
changeDisp($_REQUEST['uid']);
break;
}
mysql_close($connection);
...
function changeDisp($uid){
global $connection, $db;
$q_string = "UPDATE Questions SET Displayed = 0";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
$q_string = "UPDATE Questions SET Displayed = 1 WHERE Uid='${uid}'";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
}
?>
on the webpage I display the items and radiobuttons next to the items, the purpose is to select the radiobuttons and post to set the flag 1 for the selected item, for this reason I have a item.php file
<?php
$i = 1;
foreach ($qitem as &$q) {
$options = explode(";", $q["Options"]);
$displayed = '';
if ($q["Displayed"] == 1) { $displayed='checked="yes"'; }
echo("<div class='item' name='".$q["iUid"]."'>");
echo("<div class='count'>".$i.".</div>");
echo ("<div class='radio'><input type='radio' onclick='changeDisp("".$q["Uid"]."")' name='disp' ".$displayed."></div>");
echo("<div class='left'>");
echo("<h4>".$q["Value"]."</h4>");
echo("<div class='details'>Typ: ".$q["Type"]."</div>");
echo("<div class='details'>Skala: ".$options[0]." / ".$options[1]."</div>");
echo("</div>");
echo("</div>");
$i++;
}
?>
here I am using radiobuttons to select the related item, I checked the unique id values using firebug the values are fine, I just want to click on any radiobutton and want to trigger the onclick=changeDisp() function.
I have no idea why the page doesn't reload itself and change the selected flag to 1. Could you please help me to solve this problem?
Thanks in advance.
You cannot use an onclick function to call php function without going there with a javascript, jQuery or ajax call. You could create an ajax script to call the post.php From the item.php page and return the results to you.
Here is an example of creating the function you want. This assumes that $uid is coming from a radio button and not an actual user input. If the user can directly input something you need to use a prepared statment
function changeDisp($uid)
{
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}
$query = "UPDATE Questions SET Displayed = 1 WHERE Uid='".$uid."'";
$update = $Mysqli->query($query);
if($update)
{
return true;
}
return false;
}

Insert User Data to Database with INSERT statement

From a user form: I am trying to insert the following data:
1) First Name 2) Last Name 3) Major 4) Graduation Year
I am able to connect to the database, and select the database I need--but I am unable to insert the data from the form. I am able to create records, but the data is not being saved to the database. Basically, right now I'm creating blank forms.
The variable $uInput holds the user data. I tried passing $uInput into the function doAction(), but I believe that is where the problem is. I'm trying to figure out how to pass the user data into the function doAction().
<?php
//Call function mainline
mainline();
// Declare the function mainline
function mainline() {
$uInput = getUserInput();
$connectDb = openConnect(); // Open Database Connection
selectDb($connectDb); // Select Database
doAction($uInput);
//closeConnect();
//display();
}
//Declare function getUserInput ------------------------------------------------------------------------------------
function getUserInput() {
echo "In the function getUserInput()" . "<br/>";
// Variables of User Input
$idnum = $_POST["idnum"]; // id (NOTE: auto increments in database)
$fname = $_POST["fname"]; // first name
$lname = $_POST["lname"]; // last name
$major = $_POST["major"]; // major
$year = $_POST["year"]; // year
$action = $_POST["action"]; // action (select, insert, update, delete)
$userInput = array($idnum, $fname, $lname, $major, $year, $action);
//echo "info from getUserInput: " . $action;
return $userInput;
}
function doAction($pUserInput) {
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins") {
insert($uInput);
}
}
// Create a database connection --------------------------------------------------------
function openConnect() {
$connection = mysql_connect("localhost", "root_user", "password");
echo "Opened Connection!" . "<br/>";
if(!$connection) {
die("Database connection failed: " . mysql_error());
}
return $connection;
}
// Select a database to ----------------------------------------------------------------
function selectDb($pConnectDb) {
$dbSelect = mysql_select_db("School", $pConnectDb);
if(!$dbSelect) {
die("Database selection failed: " . mysql_error());
} else {
echo "You are in the School database! <br/>";
}
}
// function insert ---------------------------------------------------------------------
function insert($pUInput) {
$sql="INSERT INTO tblStudents (first_name, last_name, major, year)
VALUES
('$pUInput[1]','$pUInput[2]','$pUInput[3]', '$pUInput[4]')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
}
?>
Your doAction() function is buggy. You are taking the parameter into the function as $pUserInput but sending to the insert() function as $uInput.
You should do it like this:
function doAction($pUserInput)
{
// if user selects INSERT from dropdown menu, then call function insert
//and pass $uInput
if ($pUserInput[5] == "ins")
{
insert($pUserInput); // <-- FIXED: Not using correct parameter.
}
}
Change insert($uInput); function to insert($pUserInput);

Categories