my mysql table accepts NULL values on many fields, I'm updating records and my desktop app is creating a http string as follows and sending to a php script.
www.webpage/script.php?firstval=48.345345&secondval=234&thirdval=&fourthval=simon
on the db thirdval is already NULL
but the parameters in the http string may or may not hold values
do I need to :
A)pass the parameter in the http string as
b)pass the parameter in the httpstring as
c)cater for the null value in the php script(
d)not include the parameter in the http string at all
or something else
my phpscript is like so :
?php
DEFINE ('DBUSER', 'generic01');
DEFINE ('DBPW', 'genpass');
DEFINE ('DBHOST', 'mysql4.xxxxxxxxx.com');
DEFINE ('DBNAME', '_Places');
$dbc = mysqli_connect(DBHOST,DBUSER,DBPW);
if (!$dbc) {
die("Database connection failed: " . mysqli_error($dbc));
exit();
}
$dbs = mysqli_select_db($dbc, DBNAME);
if (!$dbs) {
die(" Database selection bit failed: " . mysqli_error($dbc));
exit();
}
$lat = mysqli_real_escape_string($dbc, $_GET['lat']);
$lng = mysqli_real_escape_string($dbc,$_GET['lng']);
$prox = mysqli_real_escape_string($dbc,$_GET['prox']);
$description = mysqli_real_escape_string($dbc,$_GET['description']);
$id = mysqli_real_escape_string($dbc,$_GET['id']);
$direction = mysqli_real_escape_string($dbc,$_GET['direction']);
$avoiddays = mysqli_real_escape_string($dbc,$_GET['avoiddays']);
$validfrom = mysqli_real_escape_string($dbc,$_GET['validfrom']);
$validto = mysqli_real_escape_string($dbc,$_GET['validto']);
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
$expiry = mysqli_real_escape_string($dbc,$_GET['expiry']);
$query = "UPDATE places SET rt_lat = '$lat',rt_lng= '$lng',rt_prox = '$prox', rt_description = '$description', rt_direction = '$direction',rt_avoiddays = '$avoiddays',rt_validto = '$validto',rt_validfrom = '$validfrom',rt_gefid = '$gefid',rt_expiry='$expiry' WHERE rt_id = '$id'";
$result = mysqli_query($dbc, $query) or trigger_error("Query MySQL Error: " . mysqli_error($dbc));
mysqli_close($dbc);
?>
All help appreciated,
You do not need to include it in the http request, but you have to catch that, otherwise you get an E_NOTICE error.
For all fields that can be null:
if (isset($_GET['gefid'])) {
$gefid = mysqli_real_escape_string($dbc,$_GET['gefid']);
} else {
$gefid = null;
}
PHP has no knowledge of SQL nulls. If you want a blank/not-set $_GET value to become a null in the DB, then you have to take special steps:
if(isset($_GET['lat']) || ($_GET['lat'] == '')) {
$lat = 'NULL'; // a plain PHP string with the word "null" in it
} else {
$lat = "'" . mysqli_real_escape_string($dbc, $_GET['lat']) . "'"; // note the extra quotes
}
$sql = "INSERT ... VALUES ($lat, ....)"
If you do it any other way, e.g (just as an example, yes it's sql-injection vulnerable):
$sql = "INSERT ... VALUES ('$_GET[lat]', ...)";
Then for an empty $_GET['lat'] your query would actually be
INSERT ... VALUES ('', ...)
and you'd be inserting an empty string, NOT an sql null.
Related
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 6 years ago.
Parse error: syntax error, unexpected T_VARIABLE in Z:\home\ser.ser\www\sign_up.php on line 19
Also I have error with $q = mysql_query("SELECT * FROM users WHERE (login="$login")");
Help, please.
<?php
include 'mysql_connect.php';
$login = $_POST['login'];
$password = $_POST['password'];
$b_arr['b_dd'] = $_POST['B_DD'];
$b_arr['b_mm'] = $_POST['B_MM'];
$b_arr['b_yy'] = $_POST['B_YY'];
$b_date = $b_arr['b_yy'].$$b_arr['b_mm'].$b_arr['b_dd'];
if (!isUserExist($login)) {
reg($login, $password, $b_date);
} else {
echo 'This user is exist !';
}
function reg($login, $password, $b_date) {
// NEXT LINE ERROR
$query = mysql_query("INSERT INTO users VALUES ("$login", "$password", "$b_date")");
// END ERROR
}
function isUserExist($login) {
$q = mysql_query("SELECT * FROM users WHERE (login="$login")");
$result = mysql_fetch_array($q);
if ($result) {
return true;
}
}
?>
Warning: this code is dangerous. Please read about SQL Injection and why your code is extremely problematic. In short, anything that's put into the database must be sanitized.
Now, more to your question:
You aren't handling strings correctly. If you wish to use this dangerous method of querying, you need to concatenate your values into a string. To add variables to a string you use the . operator. So, to fix this line you would need to use something like:
$qry_str = "INSERT INTO users VALUES ('" . $login . "', '" . $password . "', '" . $b_date . "')";
$query = mysql_query($qry_str);
Note: I broke it into two lines for better readability and your isUserExist() function has the same issue.
You have errors in concatenations.
Please look at here: https://www.diffnow.com/?report=jgv1m
<?php
include 'mysql_connect.php';
$login = $_POST['login'];
$password = $_POST['password'];
$b_arr['b_dd'] = $_POST['B_DD'];
$b_arr['b_mm'] = $_POST['B_MM'];
$b_arr['b_yy'] = $_POST['B_YY'];
$b_date = $b_arr['b_yy'].$$b_arr['b_mm'].$b_arr['b_dd'];
if (!isUserExist($login)) {
reg($login, $password, $b_date);
} else {
echo 'This user is exist !';
}
function reg($login, $password, $b_date) {
// NEXT LINE ERROR
$query = mysql_query("INSERT INTO users VALUES ('".$login."', '".$password."', '".$b_date."')");
// END ERROR
}
function isUserExist($login) {
$q = mysql_query("SELECT * FROM users WHERE (login='".$login."')");
$result = mysql_fetch_array($q);
if ($result) {
return true;
}
}
?>
Hi I have a problem with this method and it's driving me crazy.The query below should return one field from the database, an id where the filename is matched. Only one value should be returned. When I run the query I get an SQL object returned which looks fine:
mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 0 [type] => 0 )
However I cannot access the above query object no matter what way I try or at least I'm getting no value out of it. I did the exact same to get the package id and it works perfectly.
I used $row = $result_package_id->fetch_array(MYSQLI_ASSOC);
to get the package_id and I tried that for the module_id but it didn't work. Tried the mysqli_fetch_array and it doesn't work either. At a loss of what to do next can anyone help?
ADDED getPackageId method and if statement where the two methods are called. Every time a query is successful the id and package id are retrieved and a new object is created with the two values.
function getId($fileName){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$yModuleId = 0;
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
$result_module_id = mysqli_query($con, $query_module_id);
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
function getYPackageId($package_name){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_packageName = mysqli_real_escape_string($con, $package_name);
$query_package_id = "SELECT id FROM y_package WHERE name='" . $package_name . "'";
$result_package_id = mysqli_query($con, $query_package_id) or die("__LINE__ : " . mysqli_error($con));
while($row_package = mysqli_fetch_array($result_package_id)){
$yPackageId = $row_package['id'];
print_r($yPackageId);
print_r("</br>");
print_r("</br>");
return $yPackageId;
};
}
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
You can use
while ($row = $result->fetch_assoc()) {
$saved[] = $row;
}
but I think from your code displayed a more important issue is that you seem to be mixing procedural and object orientated SQL querying.
So:
1) Rewrite yourcode to use objects, your usage of mysqli_ functions only returns arrays.
2) or alternatively, use the current code as an array because that's what it is, not an object.
Procedural
function getId($fileName){
//this does nothing. Unless this is a custom function?
//$con = connect();
// should be:
$con = mysqli_connect(details,...);
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR); //?
die('Could not connect: ' . mysqli_error($con));
}
//$yModuleId = 0; //unneeded.
$sql_filename = mysqli_real_escape_string($con, $fileName);
$query_module_id = "SELECT id FROM y_module WHERE fileName='" . $sql_filename . "'";
//add an error feedback for debugging:
$result_module_id = mysqli_query($con, $query_module_id) or die("__LINE__.":".mysqli_error($con));
while($row_model = mysqli_fetch_array($result_module_id)){
$yModuleId = $row_model['id'];
return $yModuleId;
}
}
Object Orientated:
$query_module_id = "SELECT id FROM y_module WHERE fileName='?'";
$con = new mysqli($details,...);
$thisQuery = $con->prepare($query_module_id);
$thisQuery->bind_param("s",$sql_filename);
$thisQuery->execute();
while ($row = $thisQuery->fetch_assoc()) {
$saved[] = $row;
}
$thisQuery->close();
From this the $saved variable will be an array of results.
Additional notes:
You are using MySQL COMMIT near the bottom of your code and this is for transactions but you have not shown you've setup or begun any MySQL transactions.
You have a return inside a while statement in getYPackageId which means that the while wil only ever run once because as soon as it reaches the return it will do just that. Bad format.
Remove the semi-colon after the closing bracket of the while statement. This is bad syntax.
I figured out the problem and I feel like such an idiot! The problem was here
if($result_model && $result_package && $result_model_package) {
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
mysqli_query($con, "COMMIT");
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
I was running the commit after I was trying to get the id and package_id from the database that's why I wasn't getting any results. I changed it to this:
if($result_model && $result_package && $result_model_package) {
mysqli_query($con, "COMMIT");
$yModuleId = getId($fileName);
$yPackageId = getYPackageId($package_name);
$yIdObject = new YIds($yModuleId, $yaPackageId);
$yIdObjects [] = $yIdObject;
$message = array("success", "[SUCCESS]", "Model published successfully.",$module_id);
}
It worked perfectly. This is how the getId() method looked when I got it working
function getId($moduleName, $moduleRevision){
$con = connect();
if (!$con) {
trigger_error(mysqli_error($con), E_USER_ERROR);
die('Could not connect: ' . mysqli_error($con));
}
$sql_moduleName = mysqli_real_escape_string($con, $moduleName);
$sql_moduleRevision = mysqli_real_escape_string($con, $moduleRevision);
$query_module_id = "SELECT id, module_name, module_revision FROM y_module";
$result_module_id = mysqli_query($con, $query_module_id);
while($row = mysqli_fetch_assoc($result_module_id)){
if($row['module_name'] === $moduleName && $row['module_revision'] == $moduleRevision){
return $row['id'];
}
}
}
Thanks to Martin for all the help and the advice much appreciated! Hope this can help someone by not making the same stupid mistake as me.
So I am having a difficult time getting a variable using a mysql search command and then using it in the same script in an insert command. What am I doing wrong?
<?php
$usto= $_GET["usto"];
$itena= "item";
$sql = 'SELECT sname FROM login';
$hostname_Database = "blocked";
$database_Database = "blocked";
$username_Database = "blocked";
$password_Database = "blocked";
$mysqli = new mysqli($hostname_Database, $username_Database, $password_Database, $database_Database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$result = $mysqli->query($sql);
if ($result) {
$row = $result->fetch_assoc();
$sql = "INSERT INTO pon(mis, take)
VALUES({$row['snake']}, '" . $usto . "')"; //Here, I am trying to use the result from the previous select statement for the variable
$result = $mysqli->query($sql);
if ($result) {
...etc.
}
}
?>
You are vulnerable to SQL injection attacks. Read up about those and fix your code FIRST.
After that, realize that ->query() calls return a result HANDLE, not the actual field(s) you'd requested in your query. You have to FETCH a row of data first:
$result = $mysqli->query($sql);
$row = $result->fetch_assoc();
$sql = ".... VALUES ({$row['name_of_field']} ...)";
Note that this is STILL vulnerable to SQL injection.. it's purely to illustrate the query/fetch/insert process.
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I am getting an error and for the life of my can't figure it out. My code is kind of messy so watch out:
$hostname = ""; //SET SERVER/HOSTNAME
$dbusername = ""; //SET DATABASE USERNAME
$dbname = ""; //SET DATABASE NAME
$dbpassword = ""; //SET DATABASE USERNAME
$link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname);
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$sql = "SELECT * FROM utility WHERE `program_code` = '$program_code'";
$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT);
if (!$result)
{
echo 'Error: ', $mysqli->error;
}
while($row = $result->fetch_assoc()){
$program_code1 = $row['program_code'];
$utility_company = $row['utility_company'];
$rate = $row['rate'];
$term = $row['term'];
}
$sql1 = "INSERT INTO v88374 (id, ldc_account_num, revenue_class_desc, first_name, last_name, home_phone_num, sline1_addr, scity_name, spostal_code, marketer_name, distributor_name, service_type_desc, bill_method, enroll_type_desc, requested_start_date, plan_desc, contract_start_date, contract_end_date, fixed_commodity_amt, vendor_id, office_id, agent_id, customer_name, contact_name, result, promo_code, validation_code, email, state, bname, baddress, program_code, date) VALUES ( '','$ldc_account_num1','$revenue_class_desc','$first_name1','$last_name1', '$home_phone_num1','$sline1_addr1','$scity_name1','$spostal_code1','','$utility_company','$service_type_desc','$bill_method','$enroll_type_desc','$requested_start_date','$plan_desc','$contract_start_date','$contract_end_date','$rate','$vendor_id','$office_id','$agent_id1','$customer_name','$contact_name','$result','$promo_code','$validation_code1','$email1','$state1','$bname1','$baddress1','$program_code1', now())";
$result1 = mysqli_query($link, $sql1, MYSQLI_STORE_RESULT);
if (!$result1)
{
echo 'Error: ', $mysqli->error;
}
else if ($result1){
echo "Thank you. Information submitted.";
}
I am getting the error (in the subject of this question)when my second sql statement starts, at $sql1 = long_string_of_code
I'm thinking it's something with my variables from the first statement maybe? If I echo my variables from the first statemenet, I get them all ok. So I am not sure what the deal is. Any help is appreciated, I know this is a lot of code to go through. Thank you.
contact_name','$result','$promo_code'
Your using result in the second SQL. Its an object so you can't use it as a string. Change that variable and it should work
In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))