PHP / SQL error, unexpected variable name - php

I get the following error:
Parse error: syntax error, unexpected '$studentNo' (T_VARIABLE)
Can somebody tell me what's wrong here? I've read about this kind of error and base on it, it usually happens when there's a missing bracket, parenthesis or semi-colon but in my case I don't think I missed any..Does it have something to do with the variable itself, perhaps?
if(isset($_POST['next'])){
$studentNo = $_POST['sn'];
if(!empty($_POST['sn'])){
$check = ("SELECT * FROM student_info WHERE SN="$studentNo"");
$check1 = mysqli_query($con, $check);
if(mysql_num_rows($check1) > 0){
$errors['sn'] = "Student number already exists";
}
}
}

Your problem is that you have to concatenate the string.
But, before doing this, make sure that your SQL library protects against SQL injections.
To do this, just do:
$check = "SELECT * FROM student_info WHERE SN=" . $studentNo . ";";
// Also, remember to add a semicolon at the end of your SQL query :)
The best way to do this is to use a prepared statement. This site explains it very well.

Related

Update over 100 fields in mysql

i have 181 fields in my database named S1, S2....S181. I want to update these fields using values from inputs WITH name="S1", .....NAME="S181".
MY CODE IS
$S1=$_POST['S1'];
...
...
$S181=$_POST['S181'];
$sql=mysqli_query($conn,"update 'cap' set S1='$S1'......S181='$S181'")
I am trying something like
for ($i = 1; $i<=181; $i++ ) {
$(S$i)=$_POST['S$i'];
$sql = mysqli_query($conn, "UPDATE `cap4a` SET
S$i='$(S$i)'
WHERE IDID=".$id) or die (mysqli_error($conn));
}
Is there something wrong in the way I use S$i, because I am getting errors:
"Parse error: syntax error, unexpected '(', expecting variable (T_VARIABLE) or '$' in C:\xampp1\htdocs\update_cap4a.php on line 5" ?
I don't think it's a good idea to run 181 queries to alter the same row as you do. Instead, run one query that makes all required changes to the row. The code below will work for you:
$id = (int)$_POST['id'];//remove (int) if id IDID is a string
$snippets = [];//holds little snippets eg: S1='value1'
for($i=1;$i<=181;$i++){
$varname = "S$i"; //S1...S181
if(!isset($_POST[$varname])) continue;
$snippets[] = " $varname='$_POST[$varname]' ";
}
$sql = '"UPDATE cap SET '.implode(",",$snippets)." WHERE IDID=$id";
$result = mysqli_query($conn,$sql) or die (mysqli_error($conn));
I don't cover it in this snippet but you need to add at least two things before using this in production:
Proper error handling, for when your query fails
Prepared statements or escaped values to protect against SQL injection
Is there something wrong in the way I use S$i
To dynamically create a variable named S10 and set it to 'value' when $i=10, do:
$varname = "S$i";
$$varname = 'value'; // $$varname can also be referred to as $S10
See Variable Variables in the docs.
I would gave done it this way:
for ($i = 1; $i<=181; $i++) {
$key = 'S'.$i;
$value = $_POST[$key];
$update[] = "`{$key}` = '".$value."'";
$sql = mysqli_query($conn, "UPDATE `cap4a` SET ".join(",",$update)."
WHERE IDID=".$id) or die (mysqli_error($conn));
}

Using php Session Variables To Fetch Data From MySQL Database

I'm trying to use php session variables in a SELECT Statement to fetch the data stored in a multiple array database.
However, I am facing some challenges with my code below:
<?php
if(!empty($_SESSION['array'])) {
if($_SESSION['array'] == 'arrayname') {
$query = "SELECT '{$_SESSION['option']}' FROM '{$_SESSION['array']}' WHERE '{$_SESSION['key']}'='".mysqli_real_escape_string( $link, '{$_SESSION['value']}')."'";
if ($result=mysqli_query( $link, $query)) {
while ($row = mysql_fetch_array($result)) {
echo $row['{$_SESSION['value']}'];
}
}
mysqli_close($link); // Closing Connection with Server
}
} ?>
Any attempt to fetch the data with the above code rather displays an error messages, like;
Parse error: syntax error, unexpected 'value' (T_STRING) in C:\xampp\htdocs\content\fetchData.php on line 5
I will be much grateful for a way out to deal with this challenge.
Thanks in advance!
For your query, get your variable first:
$value = mysqli_real_escape_string( $link, $_SESSION['value']);
Then use $value rather than try and embed like you have above.
You don't need the single quotes or the curly braces around $_SESSION when you are echoing the value. Just do this:
echo $row[$_SESSION['value']];
That should fix your current error, however you still have more issues with your code. Namely you are mixing mysql and mysqli functions, which won't work. Move your code over to mysqli completely.

PHP SQL Statement not accepting Variable

I'm trying to use the following code however it is giving me errors.
Code:
$id = $_GET['id'];
$action = '['command'=>'get','target'=>'location']';
$query = "UPDATE ZeusUsers SET action = '$action' WHERE notification_id = '$id'";
$result = mysqli_query($link,$query) or exit("Error in query: $query. " . mysqli_error());
Error:
Parse error: syntax error, unexpected 'command'
If I change the $action to a standard word the statement works fine, it just seems to have issues with the single quotes and square brackets.
I've also tried using \ in front of the single quotes and it still fails.
Any ideas?
let php build the json string for you
$action = json_encode(array('command'=>'get','target'=>'location'));
You are starting and stoping a string literal with the single quotes so php is interpreting command as php code but it doesn't know what that keyword is.

Concatenate variables inside of a query

What would be the proper way to concatenate this query?
$query2= "SELECT * FROM relationships WHERE user_1= '.$_SESSION['user_id'].'
AND user_2= '.$user_id.' ";
I keep getting this error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\xampp\htdocs\beta\profile.php on line 32
What would be the proper way to concatenate this query?
To let your SQL library/client/server do it for you (while escaping special characters for free). Trying to build code by mashing strings together is relatively error prone and involves fiddly combinations of various quote characters that can become hard to maintain.
Use prepared statements and bound arguments instead.
You have an incorrect nesting of single and double quotes.
$query2= "SELECT * FROM relationships WHERE user_1= '" . $_SESSION['user_id'] . "' AND user_2= '" . $user_id . "'";
Either:
$query2 = "SELECT * FROM relationships WHERE user_1='" . $_SESSION['user_id'] . "'AND user_2='" . $user_id . "'";
Or:
$query2 = "SELECT * FROM relationships WHERE user_1='${_SESSION['user_id']}' AND user_2='$user_id'";
fixes your syntax error. However, forming queries through concatenation is a bad idea. At the very least, you should mysql_realescapestring all the arguments, if not move to using PDO.

PHP giving variable error when using SESSION

All,
I'm trying to write a mySQL query but PHP is giving me an error. The line that is giving me an error is:
$qry = "Select * from vendor_options where vendor_option_id='$_SESSION[pav_vendor_categories_$i]'";
The above code is in a for loop so that is how the $i is getting populated. The error I'm receiving is:
Parse error: syntax error, unexpected T_VARIABLE, expecting ']'
Any ideas on what is wrong? Thanks!
$sVendorId = $_SESSION['pav_vendor_categories_' . $i];
$sQuery = "SELECT * FROM vendor_options WHERE vendor_option_id='{$sVendorId}'";
This your working code.
Build vendor option ID outside of query — this will make you code more readable.
Try this;
$qry = "Select * from vendor_options where
vendor_option_id='{$_SESSION["pav_vendor_categories_{$i}"]}'";
Demo: http://codepad.org/0nHsFZ8i
should be :
$qry = "Select * from vendor_options where vendor_option_id='".$_SESSION["pav_vendor_categories_".$i]."'";
but dont do it like that... read about sql injection
hope this helps

Categories