MySQL Query Right Syntax - mysql

$query = mysqli_query($link, "SELECT *
FROM table
WHERE column=" . row_data['column'] . " ") or die(mysqli_error($link));
Can someone tell me what wrong with syntax? I honestly work on this problem in an hour but I can't figure it out up to now. I think it is on the syntax maybe my quoutes is placed on wrong?
row_data['column'] is equals to value a
If I make it hardcoded, it output expect results.
$query = mysqli_query($link, "SELECT *
FROM table
WHERE column='value a'") or die(mysqli_error($link));
Error
Unknown column 'value a' in 'where clause'

You just miss single quotes:
$query = mysqli_query($link, "SELECT *
FROM table
WHERE column='" . row_data['column'] . "' ") or die(mysqli_error($link));
In your second example you have placed single quotes around the value while in the first not.
I guess your data is coming from another query, so you can think about join to reduce number of queries.
If data is coming from a user input you should have a look at prepared statements. If you place user input directly into the query you are open to sql injections.
Last but not least if you are still learning have a look at pdo instead of mysqli

Related

How to fix "The SELECT would examine more than MAX_JOIN_SIZE rows" problem?

I am using MySQLi Procedural to run query from a MYSQL database. I have only seen how this is done using MySQLi Object-Oriented code.
It runs perfectly on localhost, but on the remote server I get an error message saying that I have more than MAX_JOIN_SIZE rows. What code do I use to fix this error?
I have looked at all the pages concerned with this error and although I know what the problem is, I can't work out how to fix it. All of the examples I have seen use MySQLi Object-Oriented code. I have tried limiting (LIMIT 30) the number of records returned, but this made no difference.
<?php
$con=mysqli_connect("localhost","******","******","ps10");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_rs4 = "SELECT * FROM student_data INNER JOIN users ON student_data.class = users.class INNER JOIN ext_writing_tbl ON student_data.id = ext_writing_tbl.id";
$rs4 = mysqli_query($con, $query_rs4)or die( mysqli_error($con) );
$row = mysqli_num_rows($rs4);
echo "There are " . $row . " students in this class";
?>
This is the complete error message.
The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay.
It should output to a table.
I am sure now that this is something set on the server and is beyond my control. How then to write a query that does not use three tables (uses INNER JOIN twice)?

Retrieve data from a specific row

I'm trying to get data from a specific row from my database.
And I get the error:
Unknown column 'Apalm' in 'where clause'
This is my code:
$naam = $_GET['naam'];
$result = mysql_query("SELECT * FROM planten WHERE naam = $naam")
or die(mysql_error());
And the picture below shows my database.
It seems like the script thinks the row is called "Apalm". But I clearly stated to search in 'naam'?
This is probably very easy to fix, but I just can't seem to find it on Google.
So please help me, or point me in the right direction. I'm very eager to learn this!
Thanks in advance!
naam column seems to be a text, so enclose its value between single quotes within the sql code as well:
"SELECT * FROM planten WHERE naam = '$naam'"
However, pls consider using either proper escaping or prepared statements to prevent sql injection.

Multiple Joins with And Statement not working

I can not seem to get this to work as expected.
"SELECT event_positions.id as ep_id, event_positions.pos_prefered_tech, event_positions.assigned_tech_id, "
. "event_schedule.id as es_id, event_schedule.event_id, event_schedule.event_day, event_schedule.event_stime,"
. "event.id as eid, event.crewer_id as cid, event.event_title, event.crewed_by,"
. "crewer.crewer_company"
. "FROM event_schedule "
. "INNER JOIN event_positions "
. "ON event_schedule.id = event_positions.event_sched_id"
. "INNER JOIN event "
. "ON event_schedule.event_id = event.id"
. "INNER JOIN crewer "
. "ON event.crewer_id = crewer.id "
. "WHERE event_schedule.event_day >= NOW() "
. "AND event.crewer_id = ?"
If i remove the AND statement it will pull all data as expected. But I need to filter for the specific crewer_id
When I try to do this I get an empty result set. No errors.
It seems like there's some spaces missing in the generated SQL text, for example, before FROM and before INNER JOIN crewer. Are you sure this SQL statement is working?
The question mark character ? doesn't look like valid SQL. So it's likely (and we're going to assume) that this SQL text is for a prepared statement, and that the question mark is intended as a placeholder for a bind variable.
If that's the case, I suspect there's a problem with the parameter bind.
I recommend you verify that the value you are providing for the bind parameter is a value that would return rows, that is, one of the values for crewer.id that's returned by the query when this predicate is omitted.
I also suggest you test using a hardcoded literal value, in place of the question mark. Choose a literal value, again, that you know will return rows.
I suspect that when you debug this, you will find the problem is with the bind parameter. (It's only a suspicion, because there's not enough information provided for me to make a determination.)

MySQL query with regexp not working in Drupal

I have the following query, courtesy of SO:
SELECT field_website_value FROM field_data_field_website WHERE field_website_value NOT REGEXP('^(https?://|www\\.)[\.A-Za-z0-9\-]+\\.[a-zA-Z]{2,4}(/\S*)?') AND field_website_value!=''
When executing this query directly in the MySQL client, it works (shows the values that don't match the pattern).
However when putting it in Drupal, it stops working, it just returns the rows which are not empty.
$query = "SELECT field_website_value FROM field_data_field_website WHERE field_website_value NOT REGEXP('^(https?://|www\\.)[\.A-Za-z0-9\-]+\\.[a-zA-Z]{2,4}(/\S*)?') AND field_website_value!=''";
$res = db_query($query)->fetchAll();
echo count($res);
echo "<pre>";print_r($res);die();
Is there any way I can use Regexp in Drupal?
Note: getting all rows and applying the regex in PHP isn't an option.
I'm no drupal expert but I bet db_query function is doing a mysql_real_escape_string() call which will mess up the regular expression, are there any other functions you can pass that won't do this?
Actually it is the {} brackets causing the issue, you need to pass the data as a variable,
$query = "SELECT field_website_value FROM field_data_field_website WHERE field_website_value NOT REGEXP('%s') AND field_website_value!=''";
$regexp = '^(https?://|www\\.)[\.A-Za-z0-9\-]+\\.[a-zA-Z]{2,4}(/\S*)?';
db_query($query, $regexp);

Using enum in drupal

I have a mysql table id,name,gender,age religion( enum('HIN','CHR','MUS') ,category(enum('IND','AMR','SPA') where last 2 are enum datatype and my code in drupal was
$sql="SELECT * FROM {emp} WHERE age=".$age." and religion=".$rel." and category=".$categ;
$result=db_query_range($sql,0,10);
while($data=db_fetch_object($result))
{
print $data->id." ".$data->name."<br>";
}
I get no result or error . I'm trying different query with each field and all are fine except using enum.
for ex: $sql='SELECT * FROM {emp} WHERE religion="'.$rel.'"';
Is there any problem in using enum datatype in drupal
Enum is not something that I believe drupal can make with the schema API, which is what you in most cases want to use for modules and stuff. Also you are lacking an ending ) in your reference to it, but I'm sure you did it right when your made the table.
Enum is only a constraint that is built into the database when inserting values. So if you try to insert an invalid value, you will insert an empty string instead. So it wont have any effect on Drupal querying to get data. It also wont have any effect when Drupal insert values, other than converting invalid values to empty strings. You might want to check the your data, to see if it is as expected. You might just get no results because your query doesn't match anything.
Another thing is the way you construct your queries is a big NO NO, as it's very insecure. What you should do is this:
db_query("SELECT ... '%s' ...", $var);
Drupal will replace %s with your var and make sure there is no SQL injection and other nasty things. %s indicates the var is a string, use %d for ints and there are a few others I can't remember just now. You can have several placeholders like this, and they will be insert in order, much like the t function.
Seconding Googletorps advise on using parameterized queries (+1). That would not only be more secure, but also make it easier to spot the errors ;)
Your original query misses some quotes around your (String) comparison values. The following should work (Note the added single quotes):
$sql = "SELECT * FROM {emp} WHERE age='" . $age . "' and religion='" . $rel . "' and category='" . $categ . "'";
The right way to do it would be something like this:
$sql = "SELECT * FROM {emp} WHERE age='%s' and religion='%s' and category='%s'";
$args = array($age, $rel, $categ);
$result = db_query_range($sql, $args ,0 , 10);
// ...