I'm having problem with my query, it inserts the same the value again and again even though the value of the variable is different.
Here is the first page. it contains a randomizer for the creation of accounts.
function getRandomString($length = 10) {
$validCharacters = "1234567890";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
$idNo=getRandomString();
function getRandomPassword($length = 6) {
$validCharacters = "qwertyuiopasdfghjklzxcvbnm1234567890";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result .= $validCharacters[$index];
}
return $result;
}
$password=getRandomPassword();
The values will then be submitted to the next page which is below. The submitted values are correct because i print them out first to check. It always inserts the value "2147483647" for the ID_No even though this is not the randomize value.
$insert = "INSERT INTO person (ID_No, P_Word, E_Status)
VALUES('$userName', '$userPass', 'Applicant')";
$result = mysql_query($insert);
How do you fix this? Is it a bug?
We can only guess given the code posted.
I don't see where $index ends up being $userName.
The sql posted shows userName being inserted as a character string, quotes around it.
ID_No is likely an integer type and thus the character string fills it up.
This should just blow up on insert so you know that this is wrong. Best practice is to use sql_mode = 'STRICT_ALL_TABLES' in the MySQL configuration file.
I think you should check data type for id_no column..You must give double data type to that column
I think what you have in mind is this : You must use the string concatenation operator (here, in PHP, it is the DOT) if you are thinking of $ symbols as variable names.
$insert = "INSERT INTO person (ID_No, P_Word, E_Status) " .
" VALUES( " .
"'" . $userName . "'" . " , " .
"'" . $userPass. "'" . " , " .
"'" . "Applicant. "'" . " ) " ;
$result = mysql_query($insert);
Related
$link = mysqli_connect("localhost", "root", "", "jeetu") or die("Error " . mysqli_error($link));
if (isset($_POST['ok'])) {
$n = $_POST['name[]'];
$c = $_POST['contact[]'];
$a = $_POST['address[]'];
$count = count($n);
for ($i = 0; $i <= $count; $i++) {
print_r($n[$i]);
print_r($c[$i]);
print_r($a[$i]); die();
$query = "insert into add (name, contact, value) values ('" . $_POST['name[$i]'] . "'," . $_POST['contact[$i]'] . ",'" . $_POST['address[$i]'] . "')";
mysqli_query($link, "$query");
}
}
If you're using a form to input this data into a database there is no way your code will work since you're getting data from one form and not from many forms.
$count = count($n); will always return 1 because you are getting one name from the form. It only works if you're reading the data from the database.
the following sql query works perfectly in phpAdmin.
SELECT response_text FROM statement_responses WHERE response_code = "s1_r1"
it doesn't work without the speech marks around response_code value.
I'm attempting to use the value of response_text in php.
for ($x = 1; $x <= 9; $x++) {
$user_response = ${"statement_" . $x . "_response"};
$sql = "SELECT response_text FROM statement_responses WHERE response_code = \"$user_response\"";
$result = mysqli_query($sql);
$value = mysqli_fetch_object($result);
echo $user_response . "<br>";
echo $sql . "<br>";
echo $result . "<br>";
echo $value . "<br>";
}
The echoes allow me to see what each of the variables contains.
I get the following:
s1_r3 (the value of $user_response)
SELECT response_text FROM statement_responses WHERE response_code = "s1_r3" (the value of $sql - which is identical to the phpAdmin query that works.)
There are no values echoed for $result or $value.
What am I doing wrong, please? Why am I not getting the values from the database into my php code?
The first parameter for the mysqli_query should be the database connection created with mysqli_connect. Similarily, the first parameter for the mysqli_fetch_object, should be the result set identifier returned by mysqli_query.
It is a good practice to check the return values from the functions you call.
firstly, thank you for all of the responses. The following code works - i.e. it returns the value contained in 'response_text' column with the selected row identified by 'response_code' for use as the value of $response_text.
for ($x = 1; $x <= 9; $x++) {
$user_response_pre = ${"statement_" . $x . "_response"};
$user_response = "\"'" . $user_response_pre . "'\"";
$sql = "SELECT response_text FROM statement_responses WHERE response_code = $user_response";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$response_text = $row[0];
${"statement_" . $x . "_complete"} .= $response_text;
}
you can write like this
for ($x = 1; $x <= 9; $x++) {
$user_response = ${"statement_" . $x . "_response"};
$sql = 'SELECT response_text FROM statement_responses WHERE response_code = "'.$user_response.'"';
$result = mysqli_query($sql);
$value = mysqli_fetch_object($result);
echo $user_response . "<br>";
echo $sql . "<br>";
echo $result . "<br>";
echo $value . "<br>";
}
I'm currently trying to compare two sets of returned values from user selects, but when I go to compare the data from the results, the elseif statement defaults, despite the information being clearly the opposite. It doesn't matter what the values are, the program always refers to the elseif. Any help would be very much appreciated. Thank you!
// DB Constant Defines
define('DB_NAME','NurseData');
define('DB_USER','root');
define('DB_PASSWORD','root');
define('DB_HOST','localhost');
$state1 = $_REQUEST['state1'];
$state2 = $_REQUEST['state2'];
$city1 = $_REQUEST['city1'];
$city2 = $_REQUEST['city2'];
$jobTitle1 = $_REQUEST['job1'];
$jobTitle2 = $_REQUEST['job2'];
function showerror() {
die("Error " . mysql_errno() . " : " . mysql_error());
}
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME, $connection) or die(mysql_error());
$query1 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state1 . "'
AND AREA_NAME='" . $city1 . "'
AND OCC_TITLE='" . $jobTitle1 . "'";
$query2 = "SELECT DISTINCT
TOT_EMP,
JOBS_1000,
A_MEAN,
A_PCT90
FROM Nurse_Local
WHERE PRIM_STATE='" . $state2 . "'
AND AREA_NAME='" . $city2 . "'
AND OCC_TITLE='" . $jobTitle2 . "'";
if (!($getPosts1 = mysql_query ($query1, $connection))) {
showerror();
}
if (!($getPosts2 = mysql_query ($query2, $connection))) {
showerror();
}
while($rows1 = mysql_fetch_array($getPosts1)) {
while($rows2 = mysql_fetch_array($getPosts2)) {
//Retrieve array values
for ($i1 = 0; $i1 < count($rows1); $i1++) {
for ($i2 = 0; $i2 < count($rows2); $i2++) {
//Assign array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$A_PCT901 = $rows1['A_PCT90'];
$A_PCT902 = $rows2['A_PCT90'];
//Convert array values to numbers
$tot_EMP1 = 0 + $tot_EMP1;
$tot_EMP2 = 0 + $tot_EMP2;
//Functions for calculating differences
/*
function compareEMP1($diffEMP1) {
$diffEMP1 = $rows1['TOT_EMP'] - $rows2['TOT_EMP'];
return $diffEMP1;
}
function compareEMP2() {
$diffEMP2 = $rows2['TOT_EMP'] - $rows1['TOT_EMP'];
return $diffEMP2;
}
*/
}
}
if($tot_EMP1 > $tot_EMP2 || $tot_EMP2 < $tot_EMP1) {
echo $tot_EMP1;//"In " . $state1 . " there are " . compareEMP1() . " more jobs than in " . $state2;
}
elseif ($tot_EMP2 > $tot_EMP1 || $tot_EMP1 < $tot_EMP2) {
echo $tot_EMP2;//"In " . $state2 . " there are " . compareEMP2() . " more jobs than in " . $state1;
}
else {
echo "<p>There was a problem comparing the employment numbers.</p>";
}
}
}
Found the answer, it was because the "numbers" were being outputted as strings, and PHP wasn't recognizing them as numbers. I resolved it by first performing a str_replace on both $tot_EMP1 and $tot_EMP2 to remove the commas and then performing a intval() on both variables. This converts them to an integer, and the logic performs as desired. Now I will need to figure out how to add the commas back in and preserve the int status of the results.
The actual code that did the converting, but please keep in mind that my DB has the info stored as strings, so part of the problem was my own failure to properly store the data:
//Assign individual array values
$tot_EMP1 = $rows1['TOT_EMP'];
$tot_EMP2 = $rows2['TOT_EMP'];
$jobs_PER1 = $rows1['JOBS_1000'];
$jobs_PER2 = $rows2['JOBS_1000'];
$a_MEAN1 = $rows1['A_MEAN'];
$a_MEAN2 = $rows2['A_MEAN'];
$a_PCT901 = $rows1['A_PCT90'];
$a_PCT902 = $rows2['A_PCT90'];
//Convert individual array values to numbers
$tot_EMP1 = str_replace(",", "", $tot_EMP1);
$tot_EMP2 = str_replace(",", "", $tot_EMP2);
$tot_EMP1 = intval($tot_EMP1);
$tot_EMP2 = intval($tot_EMP2);
$jobs_PER1 = floatval($jobs_PER1);
$jobs_PER2 = floatval($jobs_PER2);
$a_MEAN1 = str_replace(",", "", $a_MEAN1);
$a_MEAN2 = str_replace(",", "", $a_MEAN2);
$a_MEAN1 = intval($a_MEAN1);
$a_MEAN2 = intval($a_MEAN2);
$a_PCT901 = str_replace(",", "", $a_PCT901);
$a_PCT902 = str_replace(",", "", $a_PCT902);
$a_PCT901 = intval($a_PCT901);
$a_PCT902 = intval($a_PCT902);
I want to create an array or variables that can be inserted into the sql query instead of do it manually like in my code below.
Is this possible with the simple php, not using PDO, just some kind of trick that will solve this issue.
You can see that I manually inserted 10 columns and 10 values, can I do it shorter?
So, I want to have a variable/array that will consist pt1-pt10 and another that will be consisted of a[1]-a[10].
for($j=1;$j<11;$j++) {
$a[$j] = "";
}
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'my_db';
$table = 'jos_answers';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("INSERT into ".$table."(id, title, pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8, pt9, pt10) VALUES ((select id from jos_content where title='$title'),'$title','$a[1]','$a[2]','$a[3]','$a[4]','$a[5]','$a[6]','$a[7]','$a[8]','$a[9]','$a[10]')");
?>
for($j=1;$j<11;$j++) {
$a["pt".$j] = $j;
}
"INSERT into ".$table. "(id, title,".implode(",", array_keys(a)).") VALUES ((select id from jos_content where title='$title'),'$title',".implode(",", array_values(a)).")";
Try this:
$insert = "INSERT INTO" . $table . "(id, title,";
$value = " VALUES((select id from jos_content where title='$title'),'$title',";
for($x = 1; $x < 11; $x++){
$insert .= " pt" . $x . ",";
$value .= " '$a[" . $x . "]'," //this line is iffy....
}
$insert = substr($insert, 0, -1);//to remove last comma
$value = substr($value, 0, -1);//to remove last comma
$insert .= ")";//final paren
$value .= ")";//final paren
$sql = $insert . $value; //combine parts
$result = mysql_query($sql);
The reason I think that line is iffy is becuase the ' ' surronding the varibles kinda confuses me. Do you want the varibles value to be inserted to the DB? If so I would go with this line instead:
$values .= " " . $a[$x] . ",";
If you want the ' and the values go with this:
$values .= " '" . $a[$x] . "',";
Here is a working example of the code edited a bit obviously because it is not in your SQL environment and you did not give us all the variable values: http://viper-7.com/cDAcRl
Good Luck!
Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems