JSONKit - parse JSON String to PHP to MYSQL database - php

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

Related

PHP Failed to update database

it's my first time working with php and after 2h of searching for my problem i came to the conclusion that i cant find and fix it.
I hope you guys can help me!
<?php
require "./config/_sqlconnect.php";
$temp = $_POST;
$vname = "Peter";
$nname = "Hans";
$straße ="XY";
$strnr ="8";
$plz = "9031";
$ort = "würzburg";
$land ="deutschland";
$tel ="1334134";
$email ="asdas#aasd.com";
$datum ="21.03.1942";
$anrede ="herr";
$connection = mysql_connect($dbhost, $dbuser, $dbpass, $dbname) or die
("Verbindungsversuch fehlgeschlagen");
mysql_select_db($dbname, $connection) or die('DB FAIL');
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES($temp)";
$eintrag = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES ('$vname','$nname','$straße','$strnr','$plz','$ort','$land','$tel','$email','$datum','$anrede')";
$eintragen = mysql_query($eintrag);
if($eintragen == true)
{
echo 'RICHTIG';
}
else
{
echo 'FEHLER';
}?>
the Result:
Notice: Array to string conversion in C:\xampp\htdocs\aufgabe\text.php on line 23
FEHLER
As the error suggest you are passing an array, but there is needed of a string. Your $temp is an array because it's the same as $_POST. So if you are sure that you want to pass there the $temp you have to change like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('" . implode("','", $temp) . "')";
But I see that you also have all the variables also so you can pass one by one here in VALUES like this:
$sql = "INSERT INTO tadresse (vname,nname,straße,strnr,plz,ort,land,tel,email,datum,anrede) VALUES('$vname', '$nname', '$straße', ....)";
And my suggestion is to use only English characters so to change $straße to something else

null values in mysqli parameters

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.

Getting error Object of class mysqli_result could not be converted to string [duplicate]

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

Invalid query: Table doesn't exist

I am trying to insert data in table in mysql database through php code but I am always getting following error:
Invalid query: Table 'whatsup_wp1.pushDevices' doesn't exist
I am using following code:
<?php
$deviceid = $_GET["deviceid"];
$link = mysql_connect('localhost', 'whatsup_wp1', 'XSvUCl0FugzV4');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('whatsup_wp1', $link);
if (!$db_selected) {
echo 'Can\'t use whatsup_wp1 : ' . mysql_error();
}
else
{
//echo 'connect';
}
//$query = "select count(*) from city";
//$query = "insert into devices (pushID) values('".$deviceid."')";
$query = "INSERT INTO pushDevices(device) VALUES ('".$deviceid."')";
echo $query;
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
echo $result;
?>
This database have more tables and I am able to use them. I am having problem with the tables that I am creating today. They appears in phpmyadmin but somehow I am not able to get use them through my php code.
Any help may be vital for me. I have spent complete day on it.
Thanks
Pankaj
Its hard to tell by What your saying but i have a suggestion.... It looks like theres no table selected try this
it formatted like this
$query = "INSERT INTO mydb.mytable
(mytablefield)
VALUES
('myfieldvalue')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
My guess is you meant for it to be like this?
$query = "INSERT INTO whatsup_wp1.devices
(device)
VALUES
('".$deviceid."')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
And for security reasons i recommend this...
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Change to
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Personally i just use it like this
$result = mysql_query("INSERT INTO mytable
(mytablefield)
VALUES
('myfieldvalue')");
if($result){echo "Works!";}
else{die('Invalid query: ' . mysql_error());exit();}
If you are on Linux, check that the case is the same.
On windows MySql is case insensitive, on Linux, it is case sensitive.
Also, you are missing a space after pushDevice: pushDevice(...

Pass a PHP variable to a MySQL query

What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.

Categories