Hey guys am working on a project for my college and there is one last part where i am stuck. It is about the user entering data into database and has a concatenation part where am stuck. The user has to insert a prize id and based on the prize name he enters there is a concatenation part which i will explain in the last.
this is my file where the insertion takes place:
$con=mysqli_connect("localhost","xxx","yyy","zzz");
if ($_POST['pid'] == ''||$_POST['pname'] == ''||$_POST['pamt'] == '')
{
header("location:adawdins_err.php");
}
else
{
$class = $_POST['class'];
$dept = $_POST['dept'];
$did = $_POST['did'];
$dcode = $_POST['dcode'];
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="INSERT INTO prizemaster (`prizeid`, `name`, `class`, `department`, `amount`, `donorid`, `deptcode`) VALUES ('$_POST[pid]', '$_POST[pname]', '$_POST[class]', '$_POST[dept]', '$_POST[pamt]', '$_POST[did]', '$_POST[dcode]')";
if (!mysqli_query($con,$sql1))
{
die('Error: ' . mysqli_error($con));
}
else
{
header("location:adawdins_suc.php");
}
}
mysqli_close($con);
and i want the output like this:
say if the user enters "best project" in prize name then i want it like
if(pname=="Best Project")
{
pidtemp="ABC"+$pid;
}
and after this i will use pidtemp to insert in the database file!
if(pname=="Best Project")
{
pidtemp="ABC"+$pid;
}
replace above code with below
if($pname=="Best Project")
{
$pidtemp="ABC".$pid;
}
Related
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/>";
}
}
}
}
I have two tables named 'Students_tbl' and 'admission'. I want to insert admission number in both tables at the same time such that in the 'students_tbl', it is a foreign key while in the 'admission' table, it is a primary key. The 'students_tbl' has a primary key of "std_index"
I am using one html form.
The codes I have written are outputting an error. Thanks for your replies in advance
Here are the codes
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
// Check connection
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr];
$sql = "INSERT INTO students_tbl (std_index,std_national_number)
VALUES ('$identification','$National_Number')";
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}ELSE {
die ('Thank you for registering');
}
}
?>
You are missing a closing bracket and quote
You're not executing the first query before overwriting $sql
<?php
$manzu =mysqli_connect("localhost","root","MANZu1992", "cdms");
if (!$manzu) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "Please Check your connection. We were unable to connect you to the desired site.";
}
if (isset($_POST['submit'])) {
$identification = mysqli_real_escape_string($manzu, $_POST['iddd']);
$National_Number = mysqli_real_escape_string($manzu, $_POST['national_Numberr']);
$sql = "INSERT INTO students_tbl (std_index,std_national_number) VALUES ('$identification','$National_Number')";
mysqli_query($manzu,$sql);
$sql = "INSERT INTO admission (Admission_Number)VALUES($National_Number)";
if (!mysqli_query($manzu,$sql)) {
die('Error: ' . mysqli_error($manzu));
}else {
die ('Thank you for registering');
}
}
?>
<?php
$db = new mysqli("localhost", "HIDDEN", "HIDDEN", "HIDDEN");
if ($db->connect_error) {
die("Failed to connect.");
}
if (isset($_POST["title"]) && isset($_POST["description"]) && isset($_POST["url"])) {
$title = $db->real_escape_string($_POST["title"]);
$description = $db->real_escape_string($_POST["description"]);
$url = $db->real_escape_string($_POST["url"]);
$sql = "INSERT INTO video (name, description, submission_date)
VALUES ('{$title}', '{$description}', CURDATE());
INSERT INTO video_source (video_id, url)
VALUES (LAST_INSERT_ID(), '{$url}');";
if ($db->query($sql) === TRUE) {
echo "Successfully added.";
} else {
echo "Query failed.<br><br>Data: {$title} {$description} {$url}";
}
} else {
echo "Data not set.";
}
$db->close();?>
Outputs "Query failed." with the data I entered. Replacing variables such as title with constants still has the same problem. I tried the query in PHPMyAdmin and it worked fine (with constants).
It seems to be unhappy with setting the value of video_id.
Anytime you're running multiple queries with MySQLi you should use multi_query():
$db->multi_query($sql)
In addition, LAST_INSERT_ID() in your second query is not returning any sort of value. If you're looking for the last inserted value of the 1st query you have to return that prior to running the second query.
This code really made me confused.
The first and second time I ran it, it worked perfectly but after that it stopped working
Let me explain it:
I work with 2 tables.
The first table I insert to it the current date, current time and the id of the user the id I take it from the session.
Which I believe works fine.
My problem is in the second table the error I get is the error i typed in the " print " after the second insert.
this is my code :
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$con= mysql_connect($DB_HOST ,$DB_USER , $DB_PASSWORD);
if (!$con) {
die('Failed to connect to server :'.mysql_error());
}
$db=mysql_select_db($DB_DATABASE);
if (!$db) {
die("unable to select database");
}
//first table
$qry="insert into shipment values('',NOW(),CURTIME(),'".$_SESSION['con_id']."');";
$resultop=mysql_query($qry);
//to take the id frome last insert because i need it in the second insert
$SNo=mysql_insert_id();
if ($resultop) {
$options=$_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");}
// this is the second table .. my reaaal problem
$qun=$_POST['Quantit'];
$size =count($options);
for ($i =0; $i<$size; $i++) {
$qqry="insert into shipmentquantity values('".$options[$i]."','".$SNo."','".$qun[$i]."');"; // $options is array of the id's which i took from the checkbox's in the html ... $qun is array of the values i took form html ... i sure this is right ;)
$resultqun=mysql_query($qqry);
}
if ($resultqun) {
header("location: shipment_order.php");
}
else print "error in the Quantity";
}
else print "error in the shipmet";
Just add some debug statements to find out what is going wrong. Something like -
$resultqun = mysql_query($qqry) or print mysql_error();
You need to do some reading about SQL injection as this script is vulnerable. Checkout these pages on the use of prepared statements - PDO::prepare and mysqli::prepare
UPDATE - here is an example using PDO to interact with your db -
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['con_id'])) {
header("location: login.html");
exit();
}
$DB_USER ='root';
$DB_PASSWORD='';
$DB_DATABASE='';
$db = new PDO("mysql:dbname=$DB_DATABASE;host=127.0.0.1", $DB_USER, $DB_PASSWORD);
//first table
$qry = "INSERT INTO shipment VALUES(NULL, CURRENT_DATE, CURRENT_TIME, ?)";
$stmt = $db->prepare($qry);
$resultop = $stmt->execute(array($_SESSION['con_id']));
if(!$resultop){
print $stmt->errorInfo();
} else {
$SNo = $db->lastInsertId();
$options = $_POST['op'];//this is the name of the check boxe's
if (empty($options)) {
header("location: manage_itemsE.php");
exit;
}
// this is the second table .. my reaaal problem
$qun = $_POST['Quantit'];
$size = count($options);
$stmt = $db->prepare("INSERT INTO shipmentquantity VALUES(?, ?, ?)");
for($i = 0; $i < $size; $i++) {
$resultqun = $stmt->execute(array($options[$i], $SNo, $qun[$i]));
}
if($resultqun) {
header("location: shipment_order.php");
} else {
print $stmt->errorInfo();
}
}
What is your primary key for the 'shipmentquantity' table? It looks like you are trying to enter two values of '3' for the primary key and that's where it's going awry.
DESCRIBE `shipmentquanitity`
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);