Adding input from textfield to database - php

I try to add datas which are taken from a textfile to my database with a php script, here is the script:
foreach($lines as $name){
$bolunmus=explode(" ", $name);
$add = false;
if(!exist_in_db($bolunmus[0], $bolunmus[1], $bolunmus[2])){
$add = mysql_query("
INSERT INTO people(name, surname, age)
VALUES('$bolunmus[0]', '$bolunmus[1]', '$bolunmus[2]');", $con);
}
else{
echo (" could not write it.<br>");
}
if($add)
echo $bolunmus[0]." ".$bolunmus[1]." ".$bolunmus[2]." Added to database.";
}
// this is my control function, which will return
// true if data already exist in database,
// else it will return false.
function exist_in_db($name, $surname, $age){
$result = mysql_query("
SELECT * FROM people ORDER BY id
");
while($row = mysql_fetch_array($result)){
if($row['name']==$name && $row['surname']==$surname || $row['age']==$age){
echo $row."could not write it.";
return true;
}else{
return false;
}
}
}
?>
in fact, the problem is when I try to execute this script, it reads from textfile, and if that user does not exist, it adds, until here there is not any problem. But when I try to execute it again, it adds users with same output like "bla bla 0 is added to database." If I don't make any changes in text-file, I want it to control again, and if that user exists, do not add it, thanks everybody.

if($row['name']==$name && $row['surname']==$surname || $row['age']==$age)
^ ^
There should be a bracket here.
if(($row['name']==$name && $row['surname']==$surname) || $row['age']==$age)
To debug further, try var_dump($bolunmus);

Related

PDO - Test Of Empty Results

I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.

Data Not inserting into table PHP

The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.

need help inserting a default text value into mysql

end web developer, i was given a CMS done from another team and i have to link with my front-end. I have made some modifications, but due to my lack of php knowledge i have some issue here.
My users are able to fill up a form, where 1 text field is asking for their photo link. I want to check for if the value entered is not equal to what i want, then i will query insert a default avatar photo link to mysql to process.
code that i tried on php
// check if the variable $photo is empty, if it is, insert the default image link
if($photo = ""){
$photo="images/avatarDefault.png";
}
doesn't seem to work
<?php
if($_SERVER["REQUEST_METHOD"] === "POST")
{
//Used to establish connection with the database
include 'dbAuthen.php';
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
//Used to Validate User input
$valid = true;
//Getting Data from the POST
$username = sanitizeInput($_POST['username']);
$displayname = sanitizeInput($_POST['displayname']);
$password = sanitizeInput($_POST['password']);
//hash the password using Bcrypt - this is to prevent
//incompatibility from using PASSWORD_DEFAULT when the default PHP hashing algorithm is changed from bcrypt
$hashed_password = password_hash($password, PASSWORD_BCRYPT);
//Determining Type of the User
//if B - User is student
//if A - User is adin
if($_POST['type'] == 'true')
$type = 'B';
else
$type = 'A';
$email = sanitizeInput($_POST['email']);
$tutorGroup = sanitizeInput($_POST['tutorGroup']);
$courseID = sanitizeInput($_POST['courseID']);
$description = sanitizeInput($_POST['desc']);
$courseYear = date("Y");
$website = sanitizeInput($_POST['website']);
$skillSets = sanitizeInput($_POST['skillSets']);
$specialisation = sanitizeInput($_POST['specialisation']);
$photo = sanitizeInput($_POST['photo']);
// this is what i tried, checking if the value entered is empty, but doesn't work
if($photo = ""){
$photo="images/avatarDefault.png";
}
$resume = sanitizeInput($_POST['resume']);
//Validation for Username
$sql = "SELECT * FROM Users WHERE UserID= '$username'";
if (mysqli_num_rows(mysqli_query($con,$sql)) > 0){
echo 'User already exists! Please Change the Username!<br>';
$valid = false;
}
if($valid){
//Incomplete SQL Query
$sql = "INSERT INTO Users
VALUES ('$username','$displayname','$hashed_password','$type','$email', '$tutorGroup', ";
//Conditionally Concatenate Values
if(empty($courseID))
{
$sql = $sql . "NULL";
}
else
{
$sql = $sql . " '$courseID' ";
}
//Completed SQL Query
$sql = $sql . ", '$description', '$skillSets', '$specialisation', '$website', '$courseYear', '$photo', '$resume', DEFAULT)";
//retval from the SQL Query
if (!mysqli_query($con,$sql))
{
echo '*Error*: '. mysqli_error($con);
}
else
{
echo "*Success*: User Added!";
}
}
//if student create folder for them
if ($type == 'B')
{
//Store current reporting error
$oldErrorReporting = error_reporting();
//Remove E_WARNING from current error reporting level to prevent users from seeing code
error_reporting($oldErrorReporting ^ E_WARNING);
//Set current reporting error();
error_reporting($oldErrorReporting);
}
mysqli_close($con);
}
}
function sanitizeInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
i've tried finding a way on mysql to insert default values but it seem impossible, so i have no choice but to query insert through php.
I have the logic but i'm not sure how to implement on the php with my lack of knowledge, i was thinking of checking either
1) if the photo link does not have the word .png/.jpg, $photo != ".png"
2) if the photo link length is too low $.photo.length < 10
can someone help me look into the code and tell me what i'm doing wrong? Thanks!
A very simple way with default values could be:
$photo = isset($photo) ? $photo : 'images/avatarDefault.png' ;
How it works is that it first it asks if the photo is set, if it is, use all ready inserted value, otherwise insert your default value,
Another (very alike) method to use:
$photo = !empty($photo) ? $photo : 'images/avatarDefault.png' ;
UPDATE
To check if it contains a certain "extension" would be a simple rewrite
$photo = preg_match('#\b(.jpg|.png)\b#', $photo ) ? $photo : "images/avatarDefault.png" ;
This way it checks wether the text / image link in $photo contains the .png file type, if it doesn't it inserts your default image
First thing that I notice is to use double =
if($photo == ""){
//...
}

PHP If statement returning early(amateur)

I'm currently struggling with a page that allows a user to complete one of two options. They can either update an existing item in the SQL database or they can delete it. When the customer deletes an option everything runs perfectly well, however whenever a customer updated an item it displays the Query failed statement from the delete function before applying the update.
It seems obvious to me that the problem must be in my IF statement and that the DeleteButton function isn't exiting if the $deleteno variable isn't set. Any help would be appreciated. Excuse the horribly messy code PHP isn't a language I am familiar with. (I have not included the connect information for privacy reasons)
function DeleteButton(){
#mysqli_select_db($con , $sql_db);
//Checks if connection is successful
if(!$con){
echo"<p>Database connection failure</p>";
} else {
if(isset($_POST["deleteID"])) {
$deleteno = $_POST["deleteID"];
}
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
$result = #mysqli_query($con,$sql);
if((!$result)) {
echo "<p>Query failed please enter a valid ID </p>";
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
}
}
}
That is the code for the delete button and the following code is for the UpdateButton minus the connection information (which works fine).
if(isset($_POST["updateID"])) {
$updateno = $_POST["updateID"];
}
if(isset($_POST["updatestatus"])) {
if($_POST["updatestatus"] == "Fulfilled") {
$updatestatus = "Fulfilled";
} elseif ($_POST["updatestatus"] == "Paid") {
$updatestatus = "Paid";
}
}
if(isset($updateno) && isset($updatestatus)) {
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result) {
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
Once again these are incomplete functions as I have omitted the connection sections.
if(!isset($deleteno)) {
$sql = "delete from orders where orderID = $deleteno;";
Are you sure you want to execute that block if $deleteno is NOT set?
P.S. You shouldn't rely on $_POST['deleteId'] being a number. Please read about SQL injections, how to avoid them and also about using prepared statements.
I've update your code, but you need to write cleaner code ( spaces, indents, etc ) this won't only help you to learn but to find your errors easily.
<?php
function DeleteButton()
{
#mysqli_select_db($con , $sql_db);
/*
Checks if connection is successful
*/
if(!$con){
echo"<p>Database connection failure</p>";
} else {
/*
Check if $_POST["deleteID"] exists, is not empty and it is numeric.
*/
if(isset($_POST["deleteID"]) && ! empty($_POST["deleteID"]) && ctype_digit(empty($_POST["deleteID"]))
$deleteno = $_POST["deleteID"];
$sql = "delete from orders where orderID='$deleteno'";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID </p>"
} else {
echo "<p>Order $deleteno succesfully deleted</p>";
unset($deleteno);
}
} else {
echo "<p>Please enter a valid ID </p>" ;
}
}
}
/*
Part 2:
===========================================================================
Check if $_POST["updateID"] exists, is not empty and it is numeric.
Check if $_POST["updatestatus"] exists, is not empty and equal to Paid or Fullfilled
*/
if( isset($_POST["updateID"]) &&
! empty($_POST["updateID"]) &&
ctype_digit(empty($_POST["updateID"]) &&
isset($_POST["updatestatus"]) &&
! empty($_POST["updatestatus"]) &&
( $_POST["updatestatus"] == "Fulfilled" || $_POST["updatestatus"] == "Paid" ) )
{
$updateno = $_POST["updateID"];
$updatestatus = $_POST["updatestatus"];
$sql ="update orders set orderstatus='$updatestatus' where orderID=$updateno;";
$result = #mysqli_query($con,$sql);
if(!$result){
echo "<p>Query failed please enter a valid ID</p>";
} else {
echo "<p>Order: $updateno succesfully updated!</p>";
}
}
There is an error in MySQL Syntax
$sql = "delete from orders where orderID = $deleteno;";
$deleteno after orderID must be inside single quotes.
change it to this $sql = "delete from orders where orderID = '$deleteno';";

How do I check if a field in my mySQL database is empty in PHP

I would like to know how to how to check if a field (column) is empty for a specific user.
I have connected successfully to a mySQL database, I have entered a user and I have fields that are empty. I have a post form that allows users to enter information. Based on whether other fields are empty, I would like them to fill accordingly. I would like to use logic to determine whether a field is empty or not. I am using the following:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(trim($_POST['listing_link']) == '') {
}
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link1) && empty($listing_link2)) {
$listing_link2 = $_POST['listing_link'];
$listing_link2 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link2`='$listing_link2'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link2) && empty($listing_link3)) {
$listing_link3 = $_POST['listing_link'];
$listing_link3 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link3`='$listing_link3'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link3) && empty($listing_link4)) {
$listing_link4 = $_POST['listing_link'];
$listing_link4 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link4`='$listing_link4'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link4) && empty($listing_link5)) {
$listing_link5 = $_POST['listing_link'];
$listing_link5 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link5`='$listing_link5'
WHERE `email`='$emailstring'";
}
$result = mysql_query($query);
}
?>
This code checks whether there is anything entered by the user when they hit the button for the "listing_link". If not, then nothing happens. If something is entered, then it will check to determine if any of the other fields are filled (listing_link1, listing_link2...listing_link5). The $listing_link1 - 5 variables are supposed to take on the information.
I cannot get the other else ifs to run except for:
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
And continually running the code by hitting the button for the form just replaces the listing_link1 variable with the newly entered information.
Perhaps there is something wrong with the logic written here. Please help if you can.
You're not defining $listing_link1 until after you've checked to see if it's empty:
else if(empty($listing_link1))
{
$listing_link1 = $_POST['listing_link'];
Flip 'em around:
$listing_link1 = $_POST['listing_link'];
if(empty($listing_link1))
{
If I got you right, this would solve your woes:
$empty = 0;
for($i=1; $i<=5; $i++){
$varname = "listinglink$i";
if(empty($$varname)){
$empty = $i;
break;
}
}
if($empty > 0){
$update_field = "listinglink{$empty}";
$update_data = $_POST['listing_link'];
mysql_query("UPDATE users SET `$update_field`='$update_data'
WHERE email='$emailstring'");
}
What I do there is spin a loop to check which one is the first empty *listing_link* and as soon as I find it, set some variable to its number and quit the loop. From there it's pretty much simple.
What this does: $$varname = 1; is that it takes the value of $varname and tries to use it as a variable name, for example:
$test = "groovy.";
$varname = "test";
echo $$varname; // eqivalent to "echo $test"
Fun technique :)

Categories