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.
Related
I've been working for the past 5 hours on why does this if get triggered...
Let me show you the code and explain you :
<?php
require_once "ConnectDB.php";
$link2 = $link;
$key = $posthwid = "";
$err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["key"])){
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (1)";
}
else{
$key = trim($_POST["key"]);
}
$hwid = $_POST["hwid"];
if(empty($err)){
$sql = "SELECT hwid, idkey, length, created_at FROM money WHERE idkey = '" .$key. "'";
$row = mysqli_query($link, $sql);
if(mysqli_num_rows($row) < 2){
while($result = mysqli_fetch_assoc($row)) {
if($result["idkey"] == $key)
{
$err = "key";
if($result["hwid"] == "")
{
$err = "nohwid";
$sql2 = "UPDATE IceCold SET hwid = '" .$hwid. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)){
$hwid = $result["hwid"];
mysqli_close($link2);
echo "debug";
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
if ($hwid !== $result["hwid"]) {
$err = "Contact the support";
}
elseif($_SESSION["admin"] == true) {
//Do special stuff
}
else {
///do other checks
if($created_at > $date){
$err = $hwid;
} else {
$err = "The key date is too old, buy a new one.";
}
}
}
else{
$err = "The key you entered was not valid.";
}
} mysqli_close($link);
} else {
$err = "multiple entry, contact support";
}
}
} else {
$err = "Thanks for the ip (" .$_SERVER['REMOTE_ADDR']. "), have a good day! (3)";
}
echo $err;
?>
So basically, I have this Connect DB file with a mysqli_connect called $link and I'm designing a liscence API for my program. My program will send a request with the "idkey" and "hwid" and is waiting for the hwid to come back. I have an entry in my sql databse with only a key registered and I've trying to make my program wotk by generating POST request with the id and a random hwid but I've found no success. If variables are weirdly moved around, It's because of the debugging.
Right now, with my current setup, I get the Contact the support response which I don't understand why?!? The request and the key are correct if I'm able to get this awnser.
It's probably a stupid mistake but I jsut can't figure it out...
Thanks in advance for your help
Edit: the if statement I'm referring to is this:
if($hwid !== $result["hwid"])
There was a typo in the code that I fixed but it wasn't the issue,
as for the elseif, that would destroy the order of execution of the code and destroy the logic behind it(If that made sense).
Weirdly, after some tests, I found out that the second SQL request I send doesn't want to be executed ($sql2) and there is no error in httpd logs... Can you execute two requests? I tried to create $link2 but it doesn't change anything
EDIT : Found solution
if($result["hwid"] == "")
{
$sql2 = "UPDATE money SET hwid = '" .$_POST["hwid"]. "' WHERE idkey = '" .$key. "'";
if(mysqli_query($link2, $sql2)) {
$newhwid = $_POST["hwid"];
mysqli_close($link2);
}
else {
$err = "Oops! Something went wrong. Contact the support.";
}
}
elseif ($_POST["hwid"] != $result["hwid"]) {
$err = "Contact the support";
}
if($_POST["hwid"] == $newhwid || $_POST["hwid"] == $result["hwid"] ) {
/// do other checks
}
The condition before that one, if($row['hwid'] = ""), is an assignment. This code is changing the value of $row['hwid'] to an empty string, causing the condition after it to be true. I assume you meant to write == to test if $row['hwid'] is empty; otherwise it doesn't make sense to write this as an if statement.
By the way, it's not clear whether this if statement shouldn't be an else if. The rest of the branches here are else if (or elseif, which is the same in PHP), so you should consider whether you have missed out an else on this one too.
I have to search if a postal code is in my database, my table is called "test" there is only one table in my database with one column and one row, the column is named "codes", and there is an only row with the INT 63000, i have a form in my website where client enter a code, and it called a .php file which check if the value is missing or present in the database, i don't know PHP so it's hard for me... :( And my code don't work :(
SOLVED : THIS IS THE WORKING CODE :
<?php session_start(); ?>
<?php
if($_POST['code-postal'] === '') {
$hasError = true;
} else {
$variable = $_POST['code-postal'];
$code = intval($variable);
}
mysql_connect('xxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxx')
or die("I cannot connect to the database because: " . mysql_error());
mysql_select_db('xxxxxxxxxx');
$code = mysql_real_escape_string($code);
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
// on ferme la connexion à mysql
mysql_close();
?>
$sql = "SELECT COUNT(*) AS total_count FROM test WHERE codes='$code'";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$data = mysql_fetch_assoc($req);
if($data['total_count'] == 1) {
$verif = true;
}
else {
$verif = false;
}
Here is the working code.
mysql_query would return result set. You will need to use mysql_fetch_assoc function to retrieve data from that.
I guess you would have more rows in table in future, because as you mentioned in table that you have only one table with one column and one row, then there is no need of database, you can directly compare values.
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 == ""){
//...
}
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);
Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks