strong textBelow is the code used for inserting a record into the database. Script is getting executed where as the record is not getting inserted into database but the php script is getting executed with out any fail. Please help me with this.
<?php
$servername = "xxx.xx.x.xxx";
$username = "usr";
$password = "pwd";
$dbname = "Dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$postdata = json_decode(file_get_contents('php://input'), true);
$tablename = "tablename";
function guidv4($data)
{
assert(strlen($data) == 16);
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
if(is_array($postdata)){
$sql = "INSERT INTO ".$tablename." (id, ssid, address, lat, lng, state, country, city, cat, subcat, sname, createdAt,pincode) VALUES ";
$valuesArr = array();
foreach($postdata as $row){
//$loc = explode(", ", $row['loc']);
//$lat = mysqli_real_escape_string($conn, $loc[0]);
//$lng = mysqli_real_escape_string($conn, $loc[1]);
$id = guidv4(random_bytes(16));
//$id = mysqli_real_escape_string($conn, $row['id']);
$ssid = mysqli_real_escape_string($conn, $row['sname']);
$address = mysqli_real_escape_string($conn, $row['address']);
$lat = mysqli_real_escape_string($conn, $row['lat']);
$lng = mysqli_real_escape_string($conn, $row['lng']);
$state = mysqli_real_escape_string($conn, $row['state']);
$country = mysqli_real_escape_string($conn, "India");
$city = mysqli_real_escape_string($conn, $row['city']);
$cat = mysqli_real_escape_string($conn, $row['cat']);
$subcat = mysqli_real_escape_string($conn, $row['subcat']);
$sname = mysqli_real_escape_string($conn, $row['sname']);
$createdAt = mysqli_real_escape_string($conn, $row['createdAt']);
$pincode = mysqli_real_escape_string($conn, $row['pincode']);
$valuesArr[] = "('$id', '$ssid', '$address', '$lat', '$lng', '$state', '$country', '$city', '$cat', '$subcat', '$sname', '$createdAt','pincode')";
}
$sql .= implode(',', $valuesArr);
$conn->query($sql) or exit(mysql_error());
}
$conn->close();
?>
It seems that the $valuesArr array elements are not being concatenated correctly
You should separate the PHP variables from the text, using the concatenation operator ".", like so:
$valuesArr[] = "('" . $id ."', '" .$ssid . "', '" . $address ."', '" . $lat ."', '" . $lng . "', '" $state . "', '" . $country . "', '" . $city . "', '" . $cat . "', '" . $subcat ."', '" . $sname . "', '" . $createdAt . "','pincode')";
I used the following function:
function update_value($table, $field, $value, $type, $where1, $value1, $where2=NULL, $value2=NULL, $where3=NULL, $value3=NULL) {
$rows = array();
global $conn;
connect();
$value1 = "'" . $value1 . "'";
$sql = "UPDATE $table SET $field =? WHERE $where1 = $value1";
$bind1 = "'" . "$type" . "'";
if ($where2 != NULL) {
$value2 = "'" . $value2 . "'";
$sql .= " AND $where2 = $value2";
}
if ($where3 != NULL) {
$value3 = "'" . $value3 . "'";
$sql .= " AND $where3 = $value3";
}
$stmt = $conn->prepare($sql);
$stmt->bind_param($type, $value);
$stmt->execute();
$stmt->close();
$conn->close();
}
...to update the username field of a table (making sure it's a string before updating via the above function). I tried updating with a string followed by an underscore but when it showed up in the table the underscore had disappeared.
I'm new to binding parameters, is there certain things it strips out? If so I'd like to know exactly what so I can use preg_match to catch them before it updates and alert the users.
The way you manipulate with data is very dangerous.
But just to fix some potential issues keeping your logic you should surround all potential table and column names with backticks and prepare values with mysqli_real_escape_string():
$val1 = "'" . mysqli_real_escape_string($value1) . "'";
$sql = "UPDATE `$table` SET `$field` = ? WHERE `$where1` = $val1";
if (!empty($where2)) {
$value2 = "'" . mysqli_real_escape_string($value2) . "'";
$sql .= " AND `$where2` = $value2";
}
if (!empty($where3)) {
$value3 = "'" . mysqli_real_escape_string($value3) . "'";
$sql .= " AND `$where3` = $value3";
}
First off, Sorry if this has already been asked.
I looked around but couldn't find any answers for it, Or maybe I was searching using the wrong words.
I have a long SQL query that I need to execute using PHP. It requires a large number of variables to be updated.
This is what I mean:
$user = json_decode($stringWithJson);
$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '{$user->userid}', `name` = '{$user->username}', `lastlogoff` = '{$user->userlastlogoff}', `profileurl` = '{$user->userprofileurl}', `avatar` = '{$user->useravatar}', `avatarmedium` = '{$user->useravatarmedium}', `useravatarfull` = '{$user->useravatarfull}', `state` = '{$user->userprofilestate}', `realname` = '{$user->userrealname}', `timecreated` = '{$user->userprofilecreatedunix}' WHERE `id` = 1;";
mysql_query($reallyLongSqlQuery);
This works fine and all, but It's a lot of code for a single line. Is there any way I can tidy this up?
Example:
$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '" . $user->userid .
"', `name` = '" . $user->username .
"', `lastlogoff` = '" . $user->userlastlogoff .
"', `profileurl` = '" . $user->userprofileurl .
"', `avatar` = '" . $user->useravatar .
"', `avatarmedium` = '" . $user->useravatarmedium .
"', `useravatarfull` = '" . $user->useravatarfull .
"', `state` = '" . $user->userprofilestate .
"', `realname` = '" . $user->userrealname .
"', `timecreated` = '" . $user->userprofilecreatedunix .
"' WHERE `id` = 1;";
This doesn't fly off the screen in one giant line, but it looks even messier in my opinion.
Another way I've though of is predefining all the variables beforehand, Like so:
$userid = $user->userid;
$username = $user->username;
$userlastlogoff = $user->userlastlogoff;
$userprofileurl = $user->userprofileurl;
$useravatar = $user->useravatar;
$useravatarmedium = $user->useravatarmedium;
$useravatarfull = $user->useravatarfull;
$userprofilestate = $user->userprofilestate;
$userrealname = $user->userrealname;
$userprofilecreatedunix = $user->userprofilecreatedunix;
$reallyLongSqlQuery = "UPDATE `profile` SET `userid` = '{$userid}', `name` = '{$username}', `lastlogoff` = '{$userlastlogoff}', `profileurl` = '{$userprofileurl}', `avatar` = '{$useravatar}', `avatarmedium` = '{$useravatarmedium}', `useravatarfull` = '{$useravatarfull}', `state` = '{$userprofilestate}', `realname` = '{$userrealname}', `timecreated` = '{$userprofilecreatedunix}' WHERE `id` = 1;";
Once again, This works fine but there must be an easier (and tidier) way to do it.
Anyone have a solution?
Of course you should be using bindings, not a plain query string, but an array can be helpful in your case:
$data['userid'] = $user->userid;
$data['name'] = $user->username;
$data['lastlogoff'] = $user->userlastlogoff;
$data['profileurl'] = $user->userprofileurl;
$data['avatar'] = $user->useravatar;
$data['avatarmedium'] = $user->useravatarmedium;
$data['useravatarfull'] = $user->useravatarfull;
$data['state'] = $user->userprofilestate;
$data['realname'] = $user->userrealname;
$data['timecreated'] = $user->userprofilecreatedunix;
foreach ($data as $column => $value)
{
$updates[] = "$column = '$value' "; // value should be escaped!
}
$reallyLongSqlQuery = 'UPDATE profile SET '.
implode(',',$updates).
' WHERE id = 1';
I currently have this query that insert data into SQL server. But as the question can contain special characters that include ' which is single quote, it skips my query and did not insert into database.
Any idea what would work for me to be able to insert single quote data into SQL server database?
Example: Trainer's Performance.
Here's my code for inserting data into database:
$sql_array = array();
foreach ($_POST['question'] as $row => $name) {
$question = $name;
$qnsNo = $_POST['qnsNo'][$row];
$input = $_POST['input'][$row];
$options = $_POST['options'][$row];
$others = $_POST['others'][$row];
$compulsory = isset($_POST['compulsory'][$row]) ? $_POST['compulsory'][$row] : "";
$idQuery = "SELECT max(surveyID) FROM scSurveyForm WHERE createBy = '$createBy' AND writeUp = '$writeUp'";
$idResult = sqlsrv_query($conn, $idQuery);
$rows = sqlsrv_fetch_array($idResult);
$lastID = $rows[0];
$sql_array[] = "('" . $question . "'," . $lastID . ",'" . $qnsNo . "','" . $input . "','" . $options . "','" . $others . "','" . $compulsory . "')";
if (!empty($question)) {
$query_single = "INSERT INTO scFormLayout(question, surveyID, qnsNo, input, options, others, compulsory)
VALUES" . implode(', ', $sql_array);
//echo $query_single.'<br/>';
$status = sqlsrv_query($conn, $query_single);
$sql_array = array();
I have written a page that will scan a site and then extract certain code from the source. That part is working successfully, however I want to run this over multiple pages and dump the details into a database. I am stuggling to get the loop working, this is what I currently have:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
for($c=0; $c<count($links); $c++)
$racepage = file_get_contents($links[$i]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
At the moment the output for this is giving me the correct contents of the last page in the list of sites (the $links variable). Ultimately I want it to loop through the whole $links variable and then import that data, using the $query variable, into a database so I can do further analysis on it.
I hope this makes sense and you can see the error in my ways.
Hmm... There are a few issues in here...
for($c=0; $c<count($links); $c++)
This loop is executing just the next line:
$racepage = file_get_contents($links[$i]);
However, $i isn't defined, I suspect you want $c. Also, you need to place some braces around various parts... Now, this is untested, but I think you want something like:
date_default_timezone_set("australia/sydney");
$host = 'http://www.tabonline.com.au/';
$day = date(d);
$month = date(m);
$year = date(Y);
$slash = '/';
$mtgraces = '/mtgraces.html';
//Gallops Meetings on Todays racing page
$content = file_get_contents($host . $year . "/". $month . "/" . $day . $mtgraces);
preg_match_all('#<a[^<>]+href\s*=\s*[\'"](.R[0-9]+.html*)[\'"]#i', $content, $matches);
foreach ($matches[1] as $url) $links[] = "$host$year$slash$month$slash$day$slash$url";
//get the runners from each page
$final_number = array();
$final_rating = array();
$final_location = array();
$final_locationcode = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
}
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
$final_number is something you get from a racepage link right? You are using it to as $i<count($final_number). Instead i think you should use $i<count($links) there as what you want to insert is a row for each link. What you can do is move the:
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
...line to the bottom of for($c=0; $c<count($links); $c++) line which would make you code look like this starting from that point, (notice $data=array() is defined before the loop):
$data = array();
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number[] = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating[] = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location[] = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode[] = explode(",", $dblocationcode);
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[0] . "', '" . $final_rating[0] . "')";
}
if(count($queries) != 0)
{
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%hostname%"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password"; // the password specified when setting-up the database
$database = "%database"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error())
}
I think there are some problems with this code still.
Edit:I also noticed that on this line
$number_data = implode(",", $number[0]);
Wouldn't $number[0] be a string, it couldn't be an array because $number is an array of matched strings so $number[0] would be the whole matched string. This would apply to 'number_data', 'rating_data', 'location_data' and 'locationcode_data' so you can
$number_data = strip_tags($number[0]);
and then when creating the insert data:
$data[] = "('" . $final_location . "', '" . $final_locationcode . "', '" . $final_number . "', '" . $final_rating . "')";
I have managed to figure it out!
I needed to put the whole lot in the for loop, so it looks like this:
for($c=0; $c<count($links); $c++)
{
$racepage = file_get_contents($links[$c]);
preg_match_all('#<td align="right" height="18"><font color="\#ffffff">[0-9]{1,2}</font></td>#', $racepage, $number);
preg_match_all('#<font color="\#00ffff">[0-9]{1,3}</font>#', $racepage, $rating);
preg_match_all('#<B>[\w]+([\s][A-Z]+)?</B>#', $racepage, $location);
preg_match_all('#<B>[\w]+\s[0-9]+</B>#', $racepage, $locationcode);
//strip tags for storage in DB
$number_data = implode(",", $number[0]);
$dbnumber = strip_tags($number_data);
$final_number = explode(",", $dbnumber);
$rating_data = implode(",", $rating[0]);
$dbrating = strip_tags($rating_data);
$final_rating = explode(",", $dbrating);
$location_data = implode(",", $location[0]);
$dblocation = strip_tags($location_data);
$final_location = explode(",", $dblocation);
$locationcode_data = implode(",", $locationcode[0]);
$dblocationcode = strip_tags($locationcode_data);
$final_locationcode = explode(",", $dblocationcode);
//Insert into database
$data = array();
for($i=0; $i<count($final_number); $i++)
{
$data[] = "('" . $final_location[0] . "', '" . $final_locationcode[0] . "', '" . $final_number[$i] . "', '" . $final_rating[$i] . "')";
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into ratings(location, location_code, tab_no, rating) values " . implode(", ", $data);
$hostname = "%HOSTNAME"; // eg. mysql.yourdomain.com (unique)
$username = "%username%"; // the username specified when setting-up the database
$password = "%password%"; // the password specified when setting-up the database
$database = "%database%"; // the database name chosen when setting-up the database (unique)
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die("Unable to select database");
mysql_query($query) OR die(mysql_error());
}
Thank you all for your help, it seems like a great community that is here. I am sure to keep an eye on it for more fixes.