need help inserting a default text value into mysql - php

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 == ""){
//...
}

Related

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.

i need to insert some text from textarea and then update it in db as i type or save it using php ajax mysql

i have this code to save note from text area
this is my post-note.php file
<?php
include('connect.php');
if(isset($_POST['note_title'])){
$note_title = $_POST['note_title'];
$note_description = $_POST['note_description'];
$login_user_id = $_SESSION['user_id'];
$errors = array();
if($note_title == ""){
$errors['note_title'] = 'fine';
}else{
$errors['note_title'] = 'fine';
}
if($note_description == ""){
$errors['note_description'] = '<span class="note_description">Please enter something</span>';
}elseif(strlen($note_description) < "3"){
$errors['note_description'] = '<span class="note_description">your note is too short</span>';
}else{
$errors['note_description'] = 'fine';
}
if($errors['note_title'] && $errors['note_description'] == 'fine'){
$Query = "INSERT INTO notes (note_title, login_user_id, note_description, is_private)
VALUE('$note_title', '".$login_user_id."', '".$note_description."','0')";
if (!mysql_query($Query)){
die('Error: ' . mysql_error());
}
$errors['done'] = 'done';
unset($_POST['note_title']);
unset($_POST['note_description']);
}
}
echo json_encode($errors);die;
?>`
i want to insert first time as new row then want to update that row in database
In notes table, add a column id (if its not already there).
On create note page use above code.
On update note page pass id field of that note in $_POST.
So if isset($_POST['id']) write an UPDATE note ... WHERE id=$_POST['id'].
This will update already created note or will insert if its a new note.
filter user inputs before inserting though

how to update data in mysql without update image first

I want to update my data in mysql.
But, if i want update (ex. firstname), photo_profile will lost.
<?php
include 'function_page_user.php';
if(($_FILES['photo_profile']) and ($_POST['firstname']) and ($_POST['lastname']) and ($_POST['password']))
{
session_start();
include 'connect.php';
$foldername="assets/img/user/";
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$pwd = mysql_real_escape_string($_POST["password"]);
if((!empty($firstname) and !empty($lastname) and !empty($pwd)) and($_FILES['photo_profile']))
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
mysql_query ("update user set firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."' , photo_profile='".$image."' where id_user ='".$_SESSION['id']."'");
move_uploaded_file($_FILES['photo_profile']['tmp_name'], $image);
echo "<script>alert ('File Succes To edit');</script>";
$page="formubahuser.php";
echo redirectPage($page);
}
else echo "variabel empty";
}
else
echo ("your data is not complete<a href=formubahuser.php>Fill it again</a>");
?>
You have a number of major problems in your code. Before you continue, you need to read about the following topics:
1) The php mysql_ functions have been deprecated. That means the functions will be removed in future versions of php. You should use pdo or mysqli instead
2) When you store passwords in your database, they should always, always, always be encrypted.
Regarding your question, I think you are asking how to change the metadata (such as a firstname) without unsetting the photo url. Try something like this:
$updatequery = "UPDATE user SET firstname = '".$firstname."' , lastname = '".$lastname."' , password = '".$pwd."'";
if( $_FILES['photo_profile'])
{
$image = $foldername . basename ($_FILES['photo_profile'] ['name']);
$updatequery .= ", photo_profile='".$image."'";
}
$updatequery .= " where id_user ='".$_SESSION['id']."'";

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 :)

Insert php record from mysql table into a different table

I've been searching for a long time for a solution to what I feel is a very simple problem.
I have a dynamically created page with a video that has a unique id. I also have a form that a user can submit content with. I want the id of the video to be included in the submission to tableA.
This code works great only when $id = 1.
$vidq = "SELECT * FROM tutorials";
$vidresult = mysql_query($vidq);
$vidrow = mysql_fetch_array($vidresult);
//form submission
if($_POST['formname'] == "submit") {
$name = $_POST['name'];
$id = $vidrow['id'];
$errorMessage = "";
if(empty($name)) {
$errorMessage .= "<li>Please enter a valid name</li>";
}
if(empty($errorMessage)) {
$insert = "INSERT INTO tableA (videoid, name) VALUES (".$id.", ".$name.")";
mysql_query($insert);
exit();
}
}
When I change $id to = 1, it posts, but when $id to = $vidrow['id'] it doesn't post.
What am I doing wrong?
Try displaying the mysql error message by using mysql_errno/mysql_error. Eg...
if (!mysql_query($insert))
{
die('MySQL Fail (' . mysql_errno() . ') - ' . mysql_error());
}
mysql_errno() documentation - http://php.net/manual/en/function.mysql-errno.php
Have you tried to print out the contents of $id after $id = $vidrow['id'];? It might reveal why it doesn't work the way you want...
Have you thought about what might happen if a malicious (or just curious) user calls your script with ?name=%27%27%29%3b%20DROP%20TABLE%20tableA%3B?

Categories