I'm trying to create a twitter style following system for my site. When ever the script below runs is adds an "Array" inside the database instead of just the user id of the person you're trying to follow. Dunno how to fix it.
<?
session_start();
# Connect to the mysql database
include_once "library/connect_to_mysql.php";
if(isSet($_POST['mem'])){
#filter everything but numbers for security
$mem1 = preg_replace('#[^0-9]#i', '', $_POST['mem']);
$mem2 = $mem1;
#Decode the Session IDX variable and extract the user's ID from it
$decryptedID = base64_decode($_SESSION['idx']);
$id_array = explode("p3h9xfn8sq03hs2234", $decryptedID);
$my_id = $id_array[1];
$sql = mysql_query("SELECT following_array FROM Members WHERE id='$my_id' LIMIT 1");
while($row = mysql_fetch_array($sql)) {
$following = $row["following_array"];
}
$followArry1 = explode(',', $following);
if (in_array($mem1, $followArry1)) {
exit();
}
if ($followArry1 != "") {
$followArry2 = "$followArry1,$mem2";
} else {
$followArry2 = "$mem2";
}
$UpdateArray = mysql_query("UPDATE Members SET following_array ='$followArry2' WHERE id='$my_id'") or die (mysql_error());
exit();
}else{
exit();
}
?>
Any help appreciated
/////// Updated Code ////////////////////
$followArry1 = explode(",", $following);
if (in_array($mem1, $followArry1)) { exit(); }
if ($followArry1 != "") {
$followArry1 = implode(',', $followArry1 + array($mem1));
} else {
$followArry1 = $mem1;
}
$UpdateArray = mysql_query("UPDATE myMembers SET following_array ='$followArry1' WHERE id='$my_id'") or die (mysql_error());
$followArry1 is an array, which converted to string shows "Array".
See proof here (live demo: http://ideone.com/tMndH):
$followArry1 = array('a', 'b', 'c'); // just an array
$result = "$followArry1"; // it is now string containing "Array"
Try the following (example here: http://ideone.com/h5ilz):
$followArry1 = array('a', 'b', 'c');
$mem = 'd';
$followArry2 = implode(',', $followArry1 + array($mem));
I also think that the problem is with adding $mem variable to $followyArry1 array.
Try this code...
if ($followArry1 != "") {
$followArry1[] = $mem1;
$followArry1 = implode(',', $followArry1);
} else {
$followArry1 = $mem1;
}
Related
In my code am trying to verify if query is true before outputing result i have tried:
require("init.php");
if(empty($_GET["book"]) && empty($_GET["url"])) {
$_SESSION["msg"] = 'Request not valid';
header("location:obinnaa.php");
}
if(isset($_GET["book"]) && isset($_GET["url"])) {
$book = $_GET['book'];
$url = $_GET['url'];
$drs = urldecode("$url");
$txt = encrypt_decrypt('decrypt', $book);
if(!preg_match('/(proc)/i', $url)) {
$_SESSION["msg"] = 'ticket printer has faild';
header("location:obinnaa.php");
exit();
} else {
$ql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
if($count < 1) {
$_SESSION["msg"] = 'Transation has oready been made by a customer please check and try again';
header("location:obinnaa.php");
exit();
}
while($riow = mysqli_fetch_assoc($ql)) {
$id = $riow["id"];
$tqty = $riow["quantity"];
for($b = 0; $b < $tqty; $b++) {
$run = rand_string(5);
$dua .= $run;
}
}
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$split = $dua;
$show_plit = str_split($split, 5);
$b = 0;
while($row = mysqli_fetch_assoc($sql)) {
$id = $row["id"];
$qty = $row["quantity"];
$oldB = $b;
$am = " ";
for(; $b < $oldB + $qty; $b++) {
$am .= "$show_plit[$b]";
$lek = mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$id");
}
if($lek) {
$adr = urlencode($adr = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ty = encrypt_decrypt("encrypt", $txt);
$vars = array(
"book" => $ty,
"url" => $adr
);
$querystring = http_build_query($vars);
$adr = "viewbuy.php?" . $querystring;
header("location: $adr");
} else {
$_SESSION["msg"] = 'Transation failed unknow error';
header("location:obinnaa.php");
}
}
}
}
but i get to
$_SESSION["msg"]='Transation has oready been made by a customer please check and try again
even when the query is right what are mine doing wrong.
Check your return variable name from the query. You have $ql when it should be $sql.
$sql = mysqli_query($conn, "select * from books where book='$txt' AND used='loading'");
$count = mysqli_num_rows($sql);
A good IDE would flag this. NetBeans is a good free one.
Public Service Announcement:
NEVER build SQL queries straight from a URL parameter. Always sanitize your inputs and (better yet) use parameterized queries for your SQL calls. You can Google these topics for more info.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
I have this code and it works perfectly, however I want to add
mysqli_real_escape_string But how can I do that to each variable since I don't know there exact information? I want it before it gets added to the query incase special characters were added
I also realized that my id never changes, it always stays one, whats the problem with that?
Granted I do not have access to PHP right now I believe this should work and get you on prepared statements.
<?php
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$update_fields = array();
$bind_params_types = ''
$bind_params_values = array();
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$update_fields[] = '{$fieldname} = ?';
$bind_params_types .= 's';
$bind_params_values[] = $value;
}
}
$update_fields = implode(',', $update_fields);
$bind_params_values = implode(',', $value);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$update_fields} WHERE id= '$id'";
if($stmt = mysqli_prepare($conn, $query)){
$stmt->bind_param($bind_params_types,$bind_params_values);
$stmt->execute();
} else {
echo "failed";
}
}
}
I've done addon in your code before updation i've esacpe the string
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$username= $_SESSION['username'];
require "connection.php";
// GET THE DATA FROM POST IF IT EXISTS
$data = isset($_POST['data']) ? $_POST['data'] : false;
// IF IT IS A VALID ARRAY THEN PROCESS IT
if (is_array($data)) {
// LOOP THOUGH EACH SUBMITTED RECORD
foreach($data as $id => $rec) {
// START AN UPDATE STRING
$updatestr = '';
// ADD FIELD / VALUES TO UPDATE STRING
foreach($rec as $fieldname => $value) {
if($fieldname == 'id'){
continue;
}
else{
$updatestr .= "`{$fieldname}` = '{$value}',";
}
}
// REMOVE THE TRAILING ,
trim($updatestr, ',');
$updatestr = rtrim($updatestr, ',');
$updatestr = mysqli_real_escape_string($conn, $updatestr);
// CREATE THE UPDATE QUERY USING THE ID OBTAINED FROM
// THE KEY OF THIS data ELEMENT
$query = "UPDATE `call` SET {$updatestr} WHERE id= '$id'";
// SEND IT TO THE DB
$result= mysqli_query($conn, $query);
}
echo "working";
}
else {
echo "not working";
}
?>
I try to read every word after this word #EXTINF:-1
and the next line from the local file and subsequently add the result to MySQL if it does not exist.
The contents of the file looks like this:
#EXTM3U
#EXTINF:-1,name1
http://www.name1
#EXTINF:-1,name2
http://www.name2
#EXTINF:-1,name3
http://www.name3
#EXTINF:-1,name4
http://www.name4
And my code:
$file = file("file.m3u);
array_shift($file);
$count = count($file);
if($count > 0) {
foreach($file as $row) {
$pos = strpos($row, ',');
if($pos !== false){
$getname[] = substr($row, $pos + 1);
} else {
$geturl[] = $row;
} } }
$count = count($getname);
for($i=0; $i < $count; $i++){
$name = $getname[$i];
$url = $geturl[$i];
if (empty($name)) { exit; };
if (empty($url)) { exit; }
$get_user = mysql_query("select * from users where (name = '$name')");
$show_user = mysql_fetch_array($get_user);
$userid = $show_user['userid'];
$get_url = mysql_query("select * from urls where url = '$url'");
$show_url = mysql_fetch_array($get_url);
$urlid = $show_url['urlid'];
if (empty($userid) && empty($urlid)) {
$add_user = "INSERT INTO users(name)
VALUES('$name')";
mysql_query($add_user);
$userid = mysql_insert_id();
$add_url = "INSERT INTO urls(userid, url)
VALUES('$userid', '$url')";
mysql_query($add_url);
$urlid = mysql_insert_id();
}
}
My code cannot read file correctly, because when I try check the line that I had read from file, it does not work.
The info that I try to read:
name = name1
url = http://www.name1
is for every user.
This might have something to do with it
$file = file("file.m3u);
It should be
$file = file("file.m3u");
Here is my function in DB_Functions.php, i want to get two different values from two different tables in single function only here is the code what i have tried so far but the values are coming null.
public function getUserMetvalue($exname,$fname) {
$result = mysql_query("SELECT metvalue FROM fitnessactivitylist WHERE activityname='$exname'") or die(mysql_error());
$result1 = mysql_query("SELECT weight FROM users WHERE name='$fname'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
$no_of_rowss = mysql_num_rows($result1);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
if ($no_of_rowss > 0) {
$result1 = mysql_fetch_array($result1);
return $result1;
}
return $result;
} else {
//exercise name not found
return false;
}
}
here is my index.php
//TAG METVALUE
if ($tag == 'metvalue') {
$exname = $_POST['exname'];
$fname = $_POST['fname'];
$usermetvalue = $db->getUserMetvalue($exname,$fname);
if ($usermetvalue != false) {
$response["success"] = 1;
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
echo json_encode($response);
}
else {
$response["error"] = 1;
$response["error_msg"] = "No exercise found!";
echo json_encode($response);
}
}
Spot the differences:
$result = mysql_query("SELECT metvalue etc...
^^^^^^^^
$result1 = mysql_query("SELECT weight etc...
^^^^^^
$response["usermetvalue"]["exname"] = $usermetvalue["exname"];
^^^^^^
$response["usermetvalue"]["fname"] = $usermetvalue["fname"];
^^^^^
You fetch fields which aren't used later, then attempt to access fields which weren't fetched in the first place...
function a_function() {
$a = 'Learn';
$b = 'Programming.';
return array($a, $b);
}
list($one, $two) = a_function();
echo $one . ' ' . $two;
I have PHP function which checks to see if variables are set and then adds them onto my SQL query. However I am don't seem to be getting any results back?
$where_array = array();
if (array_key_exists("location", $_GET)) {
$location = addslashes($_GET['location']);
$where_array[] = "`mainID` = '".$location."'";
}
if (array_key_exists("gender", $_GET)) {
$gender = addslashes($_GET["gender"]);
$where_array[] = "`gender` = '".$gender."'";
}
if (array_key_exists("hair", $_GET)) {
$hair = addslashes($_GET["hair"]);
$where_array[] = "`hair` = '".$hair."'";
}
if (array_key_exists("area", $_GET)) {
$area = addslashes($_GET["area"]);
$where_array[] = "`locationID` = '".$area."'";
}
$where_expr = '';
if ($where_array) {
$where_expr = "WHERE " . implode(" AND ", $where_array);
}
$sql = "SELECT `postID` FROM `posts` ". $where_expr;
$dbi = new db();
$result = $dbi->query($sql);
$r = mysql_fetch_row($result);
I'm trying to call the data after in a list like so:
$dbi = new db();
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql .= " ORDER BY `time` DESC LIMIT $offset, $rowsperpage";
$result = $dbi->query($sql);
// while there are rows to be fetched...
while ($row = mysql_fetch_object($result)){
// echo data
echo $row['text'];
} // end while
Anyone got any ideas why I am not retrieving any data?
while ($row = mysql_fetch_object($result)){
// echo data
echo $row->text;
} // end while
I forgot it wasn't coming from an array!