Array to string conversion in php check my code - php

<html>
<head>
</head>
<body>
<form action="mysql.php" method="post">
First Name: <input type="text" name="fname"></br>
last Name: <input type="text" name="lname">< </br>
What is your favrite subject <input type="text" name="subject"></input> </br>
Your Age : <input type="text" name="age"></input> </br>
<input type="submit" name="submit" ></input>
<input type="reset" name="rs"></input>
</form>
<?php
if (isset($_POST\['submit'\]) ){
$_sa = mysql_connect( "localhost","Ali","pakistan");
if (!$_sa){
die("can not caonnect".msql_error());
}
/* ----------- condition ----------------------
if (empty($_POST\[fname\])) {
echo "First name required";
}
------------------condition end ----------------- */
mysql_select_db("google", $_sa );
line 46-- $sql = "INSERT INTO info (firstname,lastname,subject,age) VALUES ('$_POST \[fname\]','$_POST \[lname\]','$_POST \[subject\]', '$_POST \[age\]'')";
mysql_query($sql,$_sa);
mysql_close($_sa);
}
?>][1]
// when I run my code its give me error of
Notice: Array to string conversion in C:\xampp\htdocs\mysql.php on
line 46

Try this:
$sql = "INSERT INTO info (firstname,lastname,subject,age) VALUES ('{$_POST ['fname']}','{$_POST ['lname']}','{$_POST ['subject']}', '{$_POST ['age']}')";
Explanation:
$_POST is an array
So, you need to take care of it while accessing
And, If arrays are accessed inside String, then we should use {}
For example: {$_POST['subject']}

There is an extra single quote written at the end.

Related

PHP MySQL Error echo insert into values printing on screen

I am learning PHP MYSql and faced an error while writing a marks submission program. When i run the program in chrome, the table is coming ok but neither the values are inserting in the MySQL table nor the redirection to different webpage taking place. You will understand it more clearly in the code and screen given below
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$connection = mysql_connect("localhost","root","");
if($connection == false)
{
echo("<h3>Unable MySQL</h3>");
die();
}
$db = mysql_select_db("IGNOU",$connection);
if($db == false)
die("<h3>Unable to connect to DB</h3>");
if(isset($_POST['submit']))
{
$rcptno=mysql_real_escape_string($_POST['rcptno']);
$subdt=mysql_real_escape_string($_POST['subdt']);
$amarks=mysql_real_escape_string($_POST['amarks']);
$Vvmarks=mysql_real_escape_string($_POST['Vvmarks']);
$chk_dt=mysql_real_escape_string($_POST['chk_dt']);
$roll_no=mysql_real_escape_string($_POST['roll_no']);
$sbcode=mysql_real_escape_string($_POST['sbcode']);
$ecode=mysql_real_escape_string($_POST['ecode']);
$query1=mysql_query("insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt',
'$roll_no','$sbcode','$ecode')");
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
if($query1)
{
header("location:studentmaster.php");
}
}
?>
<fieldset style="width:400px;">
<form method="post" action="">
Reciept No.: <input type="number" name="rcptno" min="1">
<br>
Submission Date.: <input type="date" name="subdt">
<br>
Assignment Marks: <input type="number" name="amarks" max = "100">
<br>
Viva Marks: <input type="number" name="Vvmarks" max="100">
<br>
Checking Date.: <input type="date" name="chk_dt">
<br>
Roll No.: <input type="text" name="roll_no">
<br>
Subject Code.:
<input type="text" name="sbcode">
<br>
Evaluator Code:
<input type="text" name="ecode">
<br>
<input type="submit" name="submit">
</form>
</fieldset>
</body>
</html>
Screen
[This is the screen in which i have not yet clicked submit button]
[Now i have Clicked Submit button but it only displays a line...no insertion...no redirection]
Kindly help in overcoming this problem....
You're seeing the output because your using this line.
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
Also you need to make sure that you have successfully inserted or not.
For this you should use these lines of code.
if ($query1) {
header('Location: studentmaster.php');
} else {
echo 'No redirect means query failed';
var_dump(mysql_error($connection));
}
Because you're learning you can skip mysql_* functions and move to mysqli, PDO
Just replace the insert query with this
insert into assignment(`col1`,`col2`,`col3`,`col4`,`col5`, `col6`,`col7`,`col8`) values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt', '$roll_no','$sbcode','$ecode')
replace col1, col2, col3... with your mysql table columns

Using MySQL random row in a select statement afterwards

I have a data base 'School'. It has only one table - 'Words'. There are word_id, word_name, word_description in it. I want to pull a random description and display it on a page. Then I want to input a word and see if the word has the same description as the random one that was pulled. What am I doing wrong? Here is the code -
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Изпит</title>
</head>
<body>
<?php
$connection = mysqli_connect('localhost', 'root', '', 'school');
if(!$connection){
echo 'NOT OK';
exit;
}
if(isset($_POST['submit_description'])){
$q = mysqli_query($connection, ' SELECT word_description
FROM words ORDER BY rand() LIMIT 1
');
$row=mysqli_fetch_assoc($q);
if($row){
$_POST['word_description'] = $row['word_description'];
echo $_POST['word_description'];
}
}
if(isset($_POST['submit_word'])){
$word_name = $_POST['word_name'];
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
$result=mysqli_query($connection, $q2);
$count=mysqli_num_rows($result);
if($count==1){
echo 'Позна ве.';
}else{
echo 'Не позна ве.';
}
}
?>
<br><br><br>
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
</body>
</html>
I think you have some typos.
This line of code here:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
Should be like this:
$q2="SELECT * FROM words WHERE word_name='".$word_name."' and word_description='".$_POST['word_description']."'";
1) There is a typo in $_POST['word_description'] in your query:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_description='".$_POST['word_decsription']."'";
2) Also, I would recommend using the word_id instead of the word description to make the verification... you would need to write it in a <input name="word_id" type="hidden" value="..." /> in your form to pass it along.
What would be even better, to prevent people from knowing the answer by looking at the code (in case they would know what word matches what id), you could encode the value in the hidden field to be md5($word_id.$word_name) and then in your query you check "WHERE MD5(CONCAT(word_id, word_name))='".$_POST['word_md5']."'" (assuming your hidden input is now called "word_md5).
EDIT:
After looking at the HTML I see what your problem is:
<form method="POST">
<input type="submit" name="submit_description" value="Искай описание.">
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
</form>
<form method="POST">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
This should all be in the same <form> element:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_description" value="<?php echo $_POST['word_description']?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
When the form is submitted, the $_POST array should contain the word_description AND the word_name submitted.
EDIT 2:
If you wish to use the id, you would have to first add it to your SELECT query:
$q = mysqli_query($connection, ' SELECT word_id, word_description
FROM words ORDER BY rand() LIMIT 1
');
Then you'd need to set it to some variable, and then later in your HTML:
<form method="POST">
The word description is: <?php echo $_POST['word_description']; ?>
<input type="hidden" name="word_id" value="<?php echo $word_id?>">
<input type="text" name="word_name">
<input type="submit" name="submit_word" value="Провери дума.">
</form>
Your second SQL query should then look like:
$q2="SELECT * FROM words WHERE word_name='$word_name' and word_id='".$_POST['word_id']."'";
Note: it is a bad practice to change the $_POST array in your code.
This array is populated by the request sent by the client and things can get confusing if you change the values there.
It is better to create another variable and set it to the value from the $_POST (example: $word_description = $_POST['word_description'];).
This way, you can still use array_key_exists('word_description', $_POST) to verify if the client actually sent something.

php file showing syntax error when using null values

I am getting the following error message:
Parse error: syntax error, unexpected ''.$E_phone_No."'' (T_CONSTANT_ENCAPSED_STRING) in E:\Xamp\htdocs\CreateEmployee.php on line 28
What is the error, I am facing a problem and I can't find the error.
<?php
$conn=oci_connect("system","123","localhost/orcl");
ob_start();
$current_file=$_SERVER['SCRIPT_NAME'];
$massage= "";
if(isset($_POST['E_First_Name'])&&
isset($_POST['E_Last_Name'])&&isset($_POST['E_Gender'])&&
isset($_POST['E_address'])&&isset($_POST['E_phone_No'])&&
isset($_POST['E_category'])&&isset($_POST['EMP_salary'])&&
isset($_POST['work_hour'])&&isset($_POST['Date_Of_Join']) )
{
$E_First_Name= $_POST['E_First_Name'];
$E_Last_Name = $_POST['E_Last_Name'];
$E_Gender = $_POST['E_Gender'];
$E_address = $_POST['E_address'];
$E_phone_No = $_POST['E_phone_No'];
$E_category = $_POST['E_category'];
$EMP_salary = $_POST['EMP_salary'];
$work_hour =$_POST['work_hour'];
$Date_Of_Join=$_POST['Date_Of_Join'];
if(!empty($E_First_Name)&&!empty($E_Last_Name)&&
!empty($E_Gender)&&!empty($E_address)&&!empty($E_phone_No)&&
!empty($E_category)&&!empty($EMP_salary)&&!empty( $work_hour)&&!empty($Date_Of_Join))
{
$sql = "insert into Employee (E_First_Name,E_Last_Name,user_name,password,E_Gender,E_address,E_phone_No,E_category,EMP_salary,work_hour,Date_Of_Join) values('".$E_First_Name."','".$E_Last_Name."',NULL,NULL,'".$E_Gender."','".$E_address."',"'.$E_phone_No."','".$E_category .'",'".$EMP_salary.'",'". $work_hour.'","'.$Date_Of_Join.'")";
$stid = oci_parse($conn,$sql);
$r = #oci_execute($stid);
if($r)
{
echo ' data is inserted...<br>';
}
else
{
echo 'data was not inserted...<br>';
}
}
else
{
$massage = "please fill up all the form correctly<br>";
}
}
?>
<html>
<head>
<title>Create FoodItem Table</title>
<style>
body
{
background:orange;
}
</style>
<head>
<body>
fill all the forms for inserting data:<br><br>
<?php echo $massage;?>
<hr color="green">
<form action="<?php echo $current_file;?>" method="POST">
E_First_Name:<br> <input type="text" name ="E_First_Name" ><br><br>
E_Last_Name:<br> <input type="text" name="E_Last_Name" ><br><br>
E_Gender:<br> <input type="text" name="E_Gender" ><br><br>
E_address:<br> <input type="text" name ="E_address"><br><br>
E_phone_No:<br> <input type= "text" name="E_phone_No" ><br><br>
E_category:<br><input type="text" name="E_category"><br><br>
EMP_salary:<br><input type="text" name="EMP_salary" ><br><br>
work_hour:<br><input type="text"name="work_hour"><br><br>
Date_Of_Join:<br><input type="text"name="Date_Of_Join"><br><br>
<input type ="submit" value="Create employee "><br><br>
Show Employee Table
</form>
</body>
The error is caused by the quotes mismatches for the four following variables in your VALUES:
$E_phone_No $E_category $work_hour $Date_Of_Join
"'.$E_phone_No."','".$E_category .'"
To be changed to:
'".$E_phone_No."','".$E_category ."'
as well as:
'". $work_hour.'","'.$Date_Of_Join.'"
To be changed to:
'". $work_hour."','".$Date_Of_Join."'
VALUES rewrite:
('".$E_First_Name."','".$E_Last_Name."',NULL,NULL,'".$E_Gender."','".$E_address."','".$E_phone_No."','".$E_category ."','".$EMP_salary."','".$work_hour."','".$Date_Of_Join."')
You may also want to add spacing between "text" and "name=... (for clarity):
<input type="text"name="Date_Of_Join">
to:
<input type="text" name="Date_Of_Join">
It has already been addressed in a comment, that your code is vulnerable to SQL injections.
The syntax highlighter shows your error. You have a quotes issue:
$EMP_salary.'",'". $work_hour.'","'.$Date_Of_Join.'")";
^^^^^^
HERE
Change it to:
$EMP_salary.'","'. $work_hour.'","'.$Date_Of_Join.'")";
There is a wrong concatenation of your query and your variables the correct way to insert string in the query is
'".$variable."'
Somewhere you place the closing single quote before the double while you should do the opposite. So change this part
NULL,'".$E_Gender."','".$E_address."','".$E_phone_No."','".$E_category ."','".$EMP_salary."','". $work_hour."','".$Date_Of_Join."')";

Undefined variable: ... in ...on line 9

I'm trying to make a form that updates a datebase but it gives me two errors. Do you have any idea what it could be from?
The errors:
Notice: Undefined variable: Points inD:\2013.1\xampp\htdocs\ranklist_get.php on line 9
Notice: Undefined variable: Skype in D:\2013.1\xampp\htdocs\ranklist_get.php on line 9
welcome.html
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype"><br>
Points: <input type="number" id="Points"><br>
<input type="submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
mysqli_close($con);
?>
Initialize your variables with the expected values before you use them in your query.
$Points=mysqli_real_escape_string($con,$_GET["Points"]);
$Skype=mysqli_real_escape_string($con,$_GET["Skype"]);
Also make sure to add the name attribute to your form fields. name="Points" and name="Skype", otherwise it wont work.
GET variables are stored in the global $_GET array (just like POST and COOKIE). You can either use them directly in your code like so $_GET["Points"] or store them in a variable.
Please note you should use the name property on each input to specify it's key in the array.
At the top of your code put:
$Points = $_GET["Points"];
$Skype = $_GET["Skype"];
Your form should be rewritten like so:
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit">
</form>
You should also sanitize your MySQL query like so:
$query = mysqli->prepare($con, "UPDATE Persons SET Points=? WHERE Skype=?");
$query->bind_param('ss', $points, $skype);
$points = $_GET["Points"];
$skype = $_GET["Skype"];
$query->execute();
You can read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php
make HTML as
<html>
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_REQUEST['Submit']=='Submit'){
$Points=$_REQUEST['Points'];
$Skype=$_REQUEST['Skype'];
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
}
mysqli_close($con);
?>
You have to get the values before you use it.

PHP dynamic form will not INSERT into mySql

I'm working on a PHP dynamic form based on the tutorial found here:
http://blog.calendarscripts.info/dynamically-adding-input-form-fields-with-jquery/
Here is the table layout:
ID | depratecat | MinBalance | InterestRate | APY | suborder
inputted rows
ID is auto-increment.
The form fields for depratecat are visible in my code only for testing; normally the user would not be able to change this value. The value of depratecat would come from a POST value from a previous page and should be the same for all rows inputted or edited in this instance. For testing I'm declaring the value as 14.
My test page is here:
http://www.bentleg.com/fcsbadmin/dynamictest4.php
The problems:
The "Add row" script function does not work and the code won't insert new data thru form; nothing happens. No errors are shown in the Chrome console
Editing or deleting pre-existing rows seems to work.
Below is my complete test code minus the connection, Some print_r added to show the array.:
<?php
error_reporting(E_ALL);
// Connect to the DB
$link = myconnection stuff
$new_depratecat='14'; //for testing
// store in the DB
if(!empty($_POST['ok'])) {
//first delete the records marked for deletion. Why? Because we don't want to process them in the code below
if( !empty($_POST['delete_ids']) and is_array($_POST['delete_ids'])) {
// you can optimize below into a single query, but let's keep it simple and clear for now:
foreach($_POST['delete_ids'] as $id) {
$sql = "DELETE FROM tblRates_balance WHERE id=$id";
$link->query($sql);
}
}
// now, to edit the existing data, we have to select all the records in a variable.
$sql="SELECT * FROM tblRates_balance WHERE depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
// now edit them
while($rates = mysqli_fetch_array($result)) {
// remember how we constructed the field names above? This was with the idea to access the values easy now
$sql = "UPDATE tblRates_balance SET
MinBalance='".$_POST['MinBalance'.$rates['id']]."',
InterestRate='".$_POST['InterestRate'.$rates['id']]."',
APY='".$_POST['APY'.$rates['id']]."',
suborder='".$_POST['suborder'.$rates['id']]."'
WHERE id='$rates[id]'";
$link->query($sql);
}
// (feel free to optimize this so query is executed only when a rate is actually changed)
// adding new
if($_POST['add_MinBalance']!= "") {
//echo ("OKAY");
$sql = "INSERT INTO tblRates_balance (depratecat, MinBalance, InterestRate, APY, suborder) VALUES ('$new_depratecat','".$_POST['add_MinBalance']."', '".$_POST['add_InterestRate']."', '".$_POST['add_APY']."','".$_POST['add_suborder']."' );";
$link->query($sql);
}
}
// select existing rates here
$sql="SELECT * FROM tblRates_balance where depratecat='$new_depratecat' ORDER BY suborder";
$result = $link->query($sql);
?>
<html>
<head>
<title>Example of dynamically adding row and inserting into mySql with jQuery</title>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
<body>
<div style="width:90%;margin:auto;">
<h1>Example of dynamically adding row and inserting into mySql with jQuery </h1>
<form method="POST" id="newrate">
<div id="itemRows">
Minimum Balance: <input type="text" name="add_MinBalance" size="30" />
Interest Rate: <input type="text" name="add_InterestRate" />
APY: <input type="text" name="add_APY" />
Order: <input type="text" name="add_suborder" size="2"/>
<< Add data and click on "Save Changes" to insert into db. <br>
You can add a new row and make changes to existing rows all at one time and click on "Save Changes."
New entry row will appear above after saving.
<?php
// Next section does updating. let's assume you have the rate data from the DB in variable called $rates
while($rates = mysqli_fetch_array($result)): ?>
<p id="oldRow<?=$rates['id']?>">
<?php //echo $rates['id']; ?>
Minimum Balance: <input type="text" name="MinBalance<?=$rates['id']?>" value="<?=$rates['MinBalance']?>" />
Interest Rate: <input type="text" name="InterestRate<?=$rates['id']?>" value="<?=$rates['InterestRate']?>" />
APY: <input type="text" name="APY<?=$rates['id']?>" value="<?=$rates['APY']?>" />
Order: <input type="text" name="suborder<?=$rates['id']?>" value="<?=$rates['suborder']?>" />
<input type="checkbox" name="delete_ids[]" value="<?=$rates['id']?>"> Mark to delete</p>
<?php endwhile;?>
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
</div>
<script language="Javascript" type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Minimum Balance:<input type="text" name="add_MinBalance[]" value="'+frm['add_MinBalance[]'].value+'">Interest Rate:<input type="text" name="add_InterestRate[]" value="'+ frm['add_InterestRate[]'].value +'">APY:<input type="text" name="add_APY[]" value="'+frm['add_APY[]'].value+'">Order:<input type="text" name="add_suborder[]"value="'+ frm['add_suborder[]'].value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+')(this);"></p>';
jQuery('#itemRows').append(row);
frm['add_MinBalance[]'].value = '';
frm['add_InterestRate[]'].value = '';
frm['add_APY[]'].value = '';
frm['add_suborder[]'].value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
//}
</script>
</body>
</html>
The inputs in the initial form have names add_depratecat, add_MinBalance, add_InterestRate, add_APY, and add_suborder. When you add new rows, they have the same names, but with [] appended. So the original row creates single inputs, the added rows create array inputs, but they have the same names, and they conflict.
You should use the array form for the original inputs as well:
<form method="POST" id="newrate">
<div id="itemRows">
Dep_rate_cat:<input type="text" name="add_depratecat[]" size="30"/>
Minimum Balance: <input type="text" name="add_MinBalance[]" size="30" />
Interest Rate: <input type="text" name="add_InterestRate[]" />
APY: <input type="text" name="add_APY[]" />
Order: <input type="text" name="add_suborder[]" size="2"/>
so that they're consistent with the added rows.
Initially you are not adding [] in the form fields,
change <input type="text" name="add_depratecat" size="30"> to <input type="text" name="add_depratecat[]" size="30">, do the same for other fields as well.
And in foreach where you are inserting data to database use array $depratecat[] instead of string $depratecat
if(isset($_POST['add_depratecat'])) {
$depratecat = $_POST['add_depratecat']; ........
For debugging purpose write echo '<pre>'; print_r($_POST); OR var_dump($_POST); Instead of
echo '<pre>',print_r($_POST,true),'</pre>';.

Categories