Inserting multivalues from textbox into the MySQL Database using PHP - php

I'm having a problem with my PHP and MySQL project . I wanted to insert multi collumn value into the database but the truth is, im already confused by the codes. it's like this if you would like to take a look:
if(!empty($_POST['brando'])){
$A="brand = '$brando'";}
else{
$A=" ";}
if(!empty($_POST['prnameo'])){
$B="product_name = '$prnameo'";}
else{
$B=" ";}
if(!empty($_POST['prido'])){
$C="product_id = '$prido'";}
else{
$C=" ";}
if(!empty($_POST['prcolo'])){
$D="color = '$prcolo'";}
else{
$D=" ";}
if(!empty($_POST['priceo'])){
$E="price = '$priceo'";}
else{
$E=" ";}
$sqlq="UPDATE $tbl_name2 SET $A $B $C $D $E where id='$id'";
mysql_query($sqlq);
I noticed that querying multivalue command into a database requires comma such as:
mysql_query("UPDATE $tablename SET collumn1='value', collum2='value' where id='value'");
and now i cant put any comma or "," in any of those codes, making the PHP page unable to send other variable values into the server.
even if i change the coding to this:
$sqlq="UPDATE $tbl_name2 SET $A , $B , $C , $D , $E where id='$id'";
it'll produce what else but damn errors.
so i would like to ask for help if you know what i'm talking about. i know, it sounds like i've been stressed out by the codings.
ooh, this code too, i forgot to put it for these.
for ($help_given=1, $help_given++)
{
echo "Thanks";
}

Try to implode() an array with "," ,like this:
<?php
if(!empty($_POST['brando'])){
$value[] ="brand = '$brando'";
}
if(!empty($_POST['prnameo'])){
$value[] ="product_name = '$prnameo'";
}
if(!empty($_POST['prido'])){
$value[] ="product_id = '$prido'";
}
if(!empty($_POST['prcolo'])){
$value[] ="color = '$prcolo'";
}
if(!empty($_POST['priceo'])){
$value[] ="price = '$priceo'";
}
$sqlq="UPDATE $tbl_name2 SET " . implode(",",$value)." where id='$id'";
mysql_query($sqlq);
?>
Then, you'd better to use "mysql_escape_string" or "PDO::prepare" method to prevent SQL injection.

if(isset($_POST['brando']))
{
$brando=mysql_escape_string($_POST['brando']);
$A="brand = ".$brando;
}
else
{
$A=" ";
}
if(isset($_POST['prnameo']))
{
$prnameo=mysql_escape_string($_POST['prnameo']);
$B="product_name = ".$prnameo;
}
else
{
$B=" ";
}
if(isset($_POST['prido']))
{
$prido=mysql_escape_string($_POST['prido']);
$C="product_id = ".$prido;
}
else
{
$C=" ";
}
if(isset($_POST['prcolo']))
{
$prcolo=mysql_escape_string($_POST['prcolo']);
$D="color= ".$prcolo;
}
else
{
$D=" ";
}
if(isset($_POST['priceo']))
{
$priceo=mysql_escape_string($_POST['priceo']);
$E="price = ".$brando;
}
else
{
$E=" ";
}
$tbl_name="mytable";//to set
$id='primary_key';//to set
$sqlq="UPDATE $tbl_name SET $A, $B, $C, $D, $E where id='$id'";
mysql_query($sqlq);
Just put values where I have commented as //to set...

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.

Adding input from textfield to database

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

for loop is not executed /getting error like loop is not working

In my example below the for loop is not executed and / or my data is not being inserted into the database. What can I change?
<?php
include('connection.php');
{
if(isset($_POST['Submit']))
{
date_default_timezone_set('Asia/Calcutta');
$date = date('Y-m-d H:i:s', time());
for ($i=1; $i<=$_POST["NUM_STUDENTS"]; $i++) {
$STD = "STUDENT_ID".$i;
$DS = "DISCOUNT".$i;
$LV = "LEAVE".$i;
$FN = "FINE".$i;
$sql = "INSERT INTO ATTENDANCE";
$sql .= "(SESSION_ID,ORG_ID,GRADE_ID,MONTH,STUDENT_ID,DISCOUNT,LEAVE,FINE,SOURCE,CREATEDTTM,UPDDTTM,DELETE_FLAG)";
$sql .= "VALUES ";
$sql .= "('".$_POST["SESSION_ID"]."','".$_POST["ORG_ID"]."','".$_POST["GRADE_ID"]."','".$_POST["MONTH"]."','".$_POST[$STD]."','".$_POST[$DS]."','".$_POST[$LV]."','".$_POST[$FN]."' ";
$sql .= ",'".$_SESSION['login_name']."','".$date."','".$date."','N')";
$objQuery_2 = mysql_query($sql);
if($objQuery_2)
{
echo"<script>alert('Attendance Fine Added Successfully')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
else
{
echo"<script>alert('Please Check Data')</script>";
header("refresh:0;url=attendance_srch.php");
exit();
}
}
}
mysql_close($bd);
ob_flush();
}
?>
You have left a lot space here between ? and > must be ?> . [This is one of the errors]
<?=$objResult["OPERATOR_ID"];? >">
^^^
must be
<?=$objResult["OPERATOR_ID"];?>">
Array keys are case sensitive. If the actual names of the input is OPERATOR_ID, then you can't access it with $_GET['operator_id'], you have to use $_GET['OPERATOR_ID'].
Another problem is that you have an extra set of braces. So you're doing all the database code even if the if (isset($_GET['OPERATOR_ID']) is false.

PHP Function within a function within a loop :S

Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}

Categories