I have tried this 100 ways and looked all over the net:
<?php
$dbname = 'pdartist2';
$table = 'subcategories';
// query
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = $SCID');
while($row = mysql_fetch_row($result))
{
foreach($row as $cell)
"$cell";
}
mysql_free_result($result);
?>
I am trying to pass the parameter $SCID which is a number, but I can't get the syntax. If I put a number in it works. But I need to be able to pass a variable.
Using single quotes in PHP does not allow variables to be passed through. Make your query line this:
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = $SCID");
you need to use double quotes around the entire query. I have also added error checking as that is very useful to check it worked as expected
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = '$SCID' ") or die(mysql_error());
The two answers given regarding changing single quotes to double quotes are correct, however I have found the best way to accomplish what you are doing is to use single quotes for the sql, then simply append variables to the string, for example:
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = ' . $SCID);
// Or
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = ' . $SCID . ' AND someCol = ' . $someValue);
And as Nick Q. mentioned in a comment, you should prep your variables going into SQL so you don't end up the target of SQL injection attacks. My advice would be to learn PDO where you can prepare your statements then bind values.
The issue is that you're using single quote around your query and PHP won't interpret the variable in single quotes, only in double quotes. So you can write your query in one of two ways.
$result = mysql_query("SELECT SubHeaderText FROM subcategories where SCID = $SCID")
OR
$result = mysql_query('SELECT SubHeaderText FROM subcategories where SCID = '.$SCID)
Using the double quote method can look cleaner, but I personally like using the single quotes with concatenation so my editor will highlight that I'm using a variable there.
Related
I'm trying to create a dynamic code that would ready from any table with the certain name but the difference between each table name is a number that is generated by a variable: for example :
//that's how I get my variable the value for example is = 3
$pid = $GLOBALS["localid"];
//the table name for example is tablename_3
$strTable = "tablename_" .$pid;
//here's how the query should look like
$query = "SELECT * FROM . $strTable . where .....;
I'm making a mistake somewhere but can't figure it out and would appreciate a little help please
Remove the dots and also make sure you have single quotes aroung where
$query = "SELECT * FROM $strTable where '.....';
Besides the comments about do or don't build your queries like this...
You're not closing the quotes properly.
$query = "SELECT * FROM . $strTable . where .....; //Double quote not closed.
should be:
$query = 'SELECT * FROM' . $strTable . 'where .....'; //Single quoted strings concatenated with variable.
or
$query = "SELECT * FROM $strTable where ....."; //Variable inside double quoted string.
Here's The code we have tried so far.
What actually we have to do is user will input data in his selected textboxes. we want php query to combine the search result and provide output.
$query=array();
$query[] = empty($_POST['keyword_s_dec']) ? : 'cand_desc='.$_POST['keyword_s_dec'];
$query[] = empty($_POST['keyword_s_location']) ? : 'cand_location='.$_POST['keyword_s_location'];
$results = implode('AND', $query);
$sql = "SELECT * FROM candidate where '".$results."'";
$result = mysql_query($sql) or die(mysql_error());
Where keyword_s_dec & keyword_s_location are our texfield ID;
cand_desc & cand_location are database columns.
Also we are trying for SQL Injection how can we achieve this?
I did some adjustments to your code:
$query = array();
if (!empty($_POST['keyword_s_dec'])) $query[] = "cand_desc = '".$_POST['keyword_s_dec']."'";
if (!empty($_POST['keyword_s_location'])) $query[] = "cand_location = '".$_POST['keyword_s_location']."'";
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate WHERE $condition";
$result = mysql_query($sql) or die(mysql_error());
This builds a valid query:
SELECT * FROM candidate WHERE cand_desc = 'test1' AND cand_location = 'test2'
Your main issue was that you weren't inserting spaces around the AND string and single quotes for the values in the WHERE clause, but I also removed the conditional ?: operator since it made the code less readable.
Note that I only fixed the code that you wrote. It won't work if none of the POST variables are set (since then the SQL string will have a WHERE clause without any content) and you should definitely use mysql_real_escape_string() when reading the POST variables to prevent SQL injection.
I am trying to update a record in my database with values pulled from an exploded array
$arr2 = explode(",",$_POST['hidden-tags']);
//echo $arr2[0];
//insert new rows into blog post
mysql_select_db($db, $db);
$insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4] WHERE idblog = '$id' ",$dbconnet);
If I echo the values from my array one at a time it works great. Once I try to put them in the db the row turns up empty. Whats more the user may not of entered 5 items they may only have entered 1 but I dont think thats really the problem. To be honest I cant see why its currently failing at all.
I know I can save all values in one field but it will be easier as separate fieldsfor when I pull back and query later on.
if the data types of the columns are string, values must be wrap with single quotes as they are string literals. eg,
$insertq = mysql_query("UPDATE blog SET tags1 = '". $arr2[0] . "',....");
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
$insertq = mysql_query("UPDATE blog SET tags1 = $arr2[0],tags2 = $arr2[1],tags3 = $arr2[2], tags4 = $arr2[3], tags5 = $arr2[4] WHERE idblog = '$id' ",$dbconnet);
should be:
$insertq = mysql_query("UPDATE blog SET tags1 = '".$arr2[0]."',tags2 = '".$arr2[1]."',tags3 = '".$arr2[2]."', tags4 = '".$arr2[3]."', tags5 = '".$arr2[4]."' WHERE idblog = '".$id."' ,$dbconnet);
or the whole query is going to consider the variables names as part of the string
EDITED: i had the quotes inverted.
It should be like this :
$insertq = mysql_query("UPDATE blog SET tags1 = "'.$arr2[0].'",tags2 = "'.$arr2[1].'",tags3 = "'.$arr2[2].'", tags4 = "'.$arr2[3].'", tags5 = "'.$arr2[4].'" WHERE idblog = "'.$id.'" ",$dbconnet);
I think you might need to look at the datatypes of your table. If you are using varchar or text as data-types then single colon will be necessary.
$insertq = mysql_query("UPDATE blog SET tags1 =' $arr2[0]',tags2 = '$arr2[1]',tags3 = '$arr2[2]', tags4 = '$arr2[3]', tags5 = '$arr2[4]' WHERE idblog = '$id' ",$dbconnet);
Also if the idblog is integer then donot use single quotes.
hope this helps
I have an array of ID:s, and the ID:s are in this format:
Bmw_330ci_89492822
So it's a string!
Now, I have this code to find whatever is in that array, in MySQL:
($solr_id_arr is the array I mentioned above, it contains string ID:s)
ex: $solr_id_arr[0] outputs Bmw_330ci_89492822
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Problem is this wont work because (I think) that there should be quotes around each of the imploded elements in order for MySQL to find the match. The field in MySQL I am matching is of type Varchar.
Here is the $query echoed:
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282, Bmw_m5_839493889')
Do you have any other solutions for this, all I need is to find matches in MySQL which are inside this array!
Thanks
Don't surround the entire thing in quotes. It is looking for where ad_id is 'Bmw_m3_cool_565440282, test'
Use
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282', 'test')
A quick fix would be to change:
//this
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
//to this
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
This one seems complicated but it's more safer and fastest one
function escaped($str)
{
return mysql_escape_string($str);
}
$arrayOfIds = array_map("escaped", $solr_id_arr);
$solr_id_arr_imploded = implode(", ", $arrayOfIds);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Simple switch to ', ' in implode():
implode("', '", $solr_id_arr);
This, together with the hardcoded quotes in the SQL string will format them as separate items.
Previous answers will work fine.
Just make sure the strings themselves do not contain quotes. If they do, escape each string before you do the implode().
If it were my code I'd write it like this:
$solr_id_arr_imploded = "'" . implode("', '", $solr_id_arr) . "'";
$query = "SELECT * FROM my_table WHERE ad_id IN ($solr_id_arr_imploded)";
$qry_result = mysql_query($query) or die(mysql_error());
...just because it keeps all the quoting work in one place. You might also want to make sure that the array isn't empty before entering this block of code. Otherwise the SELECT will match all empty ad_id's, which probably isn't what you wanted. We're also assuming that the elements of the array don't include any quote characters (or user-provided strings that haven't been sanity-checked).
As you will see I am fetching the column, and trying to update column with new data.
$result2 line is my problem, I don't think I can add $row[0] in there. How do I do it?
$result = mysql_query("SELECT link FROM items LIMIT 3");
while($row = mysql_fetch_array($result))
{
$url=($row[0]);
$rez2 = get_final_url($url);
$result2 = mysql_query("UPDATE items SET link = $rez2 WHERE id = $row[0] LIMIT 1")
or die(mysql_error());
You should use quotes:
mysql_query("UPDATE items SET link = '{$res2}' WHERE id = $row[0]");
And it would be ideal to use mysql_escape_string() function.
So:
$rez2 = mysql_escape_string(get_final_url($url));
Also you're trying to use $row[0] as link and as id. Most likely you want $row[0] element to be an ID, and something like $row[n] where n > 0 to be a link. But if you still want to use link you should query in the following manner:
$result2 = mysql_query("UPDATE items SET link = '$res2' WHERE link = {$row[0]}");
And do not forget to escape $row
It is a good idea to use mysql_fetch_assoc() function - in this case you'll get an associative array, so you'll be able access elements by sql column names. And as result you could do something like:
$result = mysql_query("SELECT id, link FROM items LIMIT 3");
while($row = mysql_fetch_assoc($result))
{
$url=($row['link']);
$rez2 = mysql_escape_string(get_final_url($url));
$result2 = mysql_query("UPDATE items SET link = '{$res2}' WHERE id = {$row['id']}")
or die(mysql_error());
}
Also if ID is a primary key you do not need LIMIT 1 in the update query.
$row[0] is in fact valid in double-quoted strings. I think your problem is a misspelling: first you assign $rez2 a value and then in the query you use $res2.
What does get_final_url($url); do? If it doesn't surround link with quotes, and handle proper string escaping (i.e. mysql_real_escape_string), your query won't work.