multiple dynamically generated checkboxes in PHP/MySQL - php

I have a series of check boxes that are coming out of one MySQL table:
<?php
$result = mysql_query("SELECT * FROM strategies");
if (!$result) {
die("Database query failed: " . mysql_error());
}
while($row = mysql_fetch_array($result)) {
$strategylist = $row['name'];
$strategyname = htmlspecialchars($row['name']);
echo '<input type="checkbox" name="strategy[]" value="' . $strategylist . '" />' . $strategyname;
}
?>
I want to be able to store multiple "strategies" to each row on a "studies" table, so I am employing another table (sslink) to store the id of the study and the name of the strategy. This is partly because there will be an ever growing number of "strategies", so they need to be stored in the database. This is the code I'm currently using:
<?php
if(isset($_POST['update1']))
{
$strategy=serialize($_POST['strategy']); //line 66, where the warning is happening
if(!get_magic_quotes_gpc())
{
$strategy = addslashes($strategy);
}
// update the article in the database
$query ="INSERT INTO sslink('study_id', 'strategyname') VALUES ('".$_GET['id']. "', '" .$strategy. "')";
mysql_query($query) or die('Error : ' . mysql_error());
$cacheDir = dirname(__FILE__) . '/cache/';
$cacheFile = $cacheDir . '_' . $_GET['id'] . '.html';
#unlink($cacheFile);
#unlink($cacheDir . 'index.html');
echo "<b>Article '$title' updated</b>";
$strategy = stripslashes($strategy);
}
?>
And this is the error that gets returned:
Notice: Undefined index: strategy in /casestudyform.php on line 66
Error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''study_id', 'strategyname') VALUES ('1', 'N;')' at line 1
Does anyone know how to fix this? or a better way to do it?
Thanks in advance!

Try this:
$query ="INSERT INTO sslink (study_id, strategyname) VALUES ('".$_GET['id']. "', '" .$strategy. "')";

Undefined index suggests that $_POST['strategy'] wasn't set. Could you do a sanity check that your form has it? Also, an echo of the actual query would be nice.

You have two errors that are unrelated to one another:
Notice: Undefined index: strategy in /casestudyform.php on line 66
As #montooner points out, this notice is from PHP, because the $_POST array contains no value for the 'strategy' key. That is, the form was submitted with no strategy checkbox checked. You should test that the key exists before trying to reference it.
if (array_key_exists('strategy', $_POST)) ...
Error : You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''study_id', 'strategyname') VALUES ('1', 'N;')' at line 1
This is an SQL parsing error. You have put single-quotes around the columns in your INSERT statement. In SQL, single-quotes delimit string constants, not column names.
If you need to delimit column names (because they contain SQL keywords, whitespace, special characters, etc.), you should use back-quote in MySQL or double-quotes in ANSI SQL.
Also be careful of SQL injection. Don't assume that the HTTP request parameters contain only integers or friendly strings. Filter the values or escape them before you use them in SQL. The addslashes() function is not a good solution to protect against SQL injection.
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$strategy_esc = mysql_real_escape_string($strategy);
$query ="INSERT INTO sslink(`study_id`, `strategyname`)
VALUES ($id, '$strategy_esc')";

Related

Query working in phpMyAdmin but not php - You have an error in your SQL syntax;

I have a simple query which works in phpMyAdmin but not via mysqli_query:
$update_sql = "
UPDATE db SET db.period = ('January-2017') WHERE db.column between '2016-12-16' and '2017/01/29';
UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26';
";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}
The output from mysqli_error() gives:
SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE db SET db.period' at line 2
Ive tried surrounding the field names with '`', copying the output from the echo statement to PHP to see if the generated string works the same, but still no joy.
There are more than one issues like, what are you trying to update here:
db.period = ('January-2017')
what is the datatype of db.period here and the condition:
WHERE db.column between '2016-12-16' and '2017/01/29';
here you are using two different date formats. Resolve these issues and than run the query again.
I think your second UPDATE line contains a redundant semicolon.
Try the simple test - does it work for a single UPDATE line?
$update_sql = "UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26'";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}
mysqli_multi_query() not mysqli_query()
For anyone else that comes accross this, as per #Lawrence Cherone's comment, it was actually something simple - using mysqli_multi_query() instead of mysqli_query()
$update_sql = "
UPDATE db SET db.period = ('January-2017') WHERE db.column between '2016-12-16' and '2017/01/29';
UPDATE db SET db.period = ('February-2017') WHERE db.column between '2017-01-30' and '2017/02/26';
";
echo '<p>'.$update_sql.'</p>';
$result_mysqli_query=mysqli_multi_query($link,$update_sql);
if(! $result_mysqli_query) {
die("SQL Error: " . mysqli_error($link));
}

keep getting a syntax error (php / mysql)

php/mysql
I keep getting this error: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1".
I'm trying hard to make this query to happen. It works, it inserts into the mysql database but this error appears every time. I've tried to use everything in the same line, changed double quotes to single quotes, removed all the whitespaces inserting everything in the samen line, changing the way I pass the variables({$variable} to '.$variable.') and everything else. I've seen a couple of stackoverflow questions related to this but with different solutions.
I know that we can't pass '' in a numeric fields.
I think I'm out of options now. Need help!
This error keeps showing but the data is correctly inserted in my table
here is the code:
$user_id = get_current_user_id();
$prescription_name = $_POST['prescription_name'];
$date_created = date('Y-m-d');
$last_updated = date('Y-m-d');
$right_eye_sphere = $_POST['right_eye_sphere'];
$left_eye_sphere = $_POST['left_eye_sphere'];
$right_eye_cylinder = $_POST['right_eye_cylinder'];
$left_eye_cylinder = $_POST['left_eye_cylinder'];
$right_eye_axis = $_POST['right_eye_axis'];
$left_eye_axis = $_POST['left_eye_axis'];
$pd = $_POST['pd'];
$date_of_birth = $_POST['date_of_birth'];
$file_path = $_POST['file_path'];
$add_query = "INSERT INTO wew_prescription (
prescription_id,
user_id,
prescription_name,
date_created,
last_updated,
right_eye_sphere,
left_eye_sphere,
right_eye_cylinder,
left_eye_cylinder,
right_eye_axis,
left_eye_axis,
pd,
date_of_birth,
file_path
) Values (
NULL,
{$user_id},
'{$prescription_name}',
'{$date_created}',
'{$last_updated}',
'{$right_eye_sphere}',
'{$left_eye_sphere}',
'{$right_eye_cylinder}',
'{$left_eye_cylinder}',
'{$right_eye_axis}',
'{$left_eye_axis}',
'{$pd}',
'{$date_of_birth}',
'{$file_path}'
)";
$sql = $dbCon->query($add_query);
if (!mysqli_query($dbCon,$sql)){
die('Error: ' . mysqli_error($dbCon));
}else{
mysqli_query($dbCon,$sql);
echo "dados atualizados!";
}
The error is coming from this line:
if (!mysqli_query($dbCon,$sql)){
$sql contains the result of
$dbCon->query($add_query);
Since that query was successful, $sql contains TRUE. mysqli_query() requires the second argument to be a string, so TRUE becomes "1", so you're effectively doing:
if (!mysqli_query($dbCon, "1")) {
That's not a valid query, so you get an error.
I think what you really meant to do was:
if (!$sql) {
die('Error: ' . $dbCon->error);
} else {
echo "dados atualizados!";
}
You don't need to keep calling mysqli_query() repeatedly.
You should also learn to code using prepared statements instead of substituting variables into the query, to prevent SQL injection.

What defines the PHP error: Call to a member function fetch_object() on a non-object

I have been wondering on this question for a while. I have two PHP programs that are almost exactly identical except for the fact that on of them is a function and the other isn't. Furthermore one works and the other send back the error:
Call to a member function fetch_object() on a non-object
I fixed the one that wasn't working by omitting the variables and inserting definitive strings and adding $con->errno instead of mysqli_errno. However, when I replaced the strings with the variables again the problem returned.
So, my question is: what causes this error and how would I fix it. Also, why is the error coming up in the second code and not the first?
The First Code (works)
<?php
$con = new mysqli("database info");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $con->query("SELECT coordinator, announcements, description, comments, picture FROM Class_data WHERE class_year = '" .$class. "';");
$result_row = $stmt->fetch_object();
$coordinator = $result_row->coordinator;
$announcement = $result_row->announcements;
$description = $result_row->description;
$comments = $result_row->comments;
$picturepath = $result_row->picture;
mysqli_error($con);
mysqli_close($con);
if ($picturepath == "")
{
$picturepath = "../images/AlumnLogo.png";
}
?>
Second Code (doesn't work)
<?php
function fetch($page, $content1, $content2, $content3)
{
$con = new mysqli("database info");
if ($con->errno)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = $con->query("SELECT '" .$content1. "' , '" .$content2. "' , '" .$content3. "' FROM '" .$page. "';");
$result_row = $stmt->fetch_object();
$content = array();
$content[0] = $result_row->body;
$content[1] = $result_row->calendar;
$content[2] = $result_row->announcements;
$output = implode("--",$content);
mysqli_error($con);
mysqli_close($con);
return $output;
}
?>
Thanks alot!
You are quoting your column names using single quotes. You cannot do that, you need to quote table- and column names using backticks (in case of reserved words, spaces, etc.) and only (non-integer...) values need to be quoted using single or double quotes.
Change your code to:
$stmt = $con->query("SELECT `" .$content1. "` , `" .$content2. "` , `" .$content3. "` FROM `" .$page. "`;");
^ All these
By the way, I assume you are using a white-list for your table- and column names. If not, you should to avoid sql injection.
It is also a good idea to add error handling to your database calls. An easy way using mysqli, is to put mysqli_report(MYSQLI_REPORT_STRICT); at the start of your script. This will cause mysqli to throw exceptions so that you do not have to check for individual errors on each database call.
The error message simply means that you try to call a method on something that is not an object. The problem is that $stmt is not an object!
This happens because there is an error in your SQL Statemetn. $con->query() retuns false in such a case. Therefore, what you try to execute is something like false->fetch_object();. And false isn't an object...
Try to print your generated SQL Statement. It will probabely contain some syntax errors. Fix those, and it will work

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '

The code below is used when the user enters a youtube url it get the youtube id from the url. It then get the title for that video with that id. That is then inserted into a database and recalled to display the image of the video associated with that id.
if i use this youtube url http://www.youtube.com/watch?v=p64tAbP-nHE or and other youtube url. If the title of that youtube url contains a ' ie(2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3) i get the error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Callaghan & Gavin Sheehan - Stage 3'' at line 1
Any help would be great, thanks in advance.
Here is my code:
<?php
include 'dataconnection.php';
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
$url = $_POST['set_video'];
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
$youtube_id = $my_array_of_vars['v'];
$info = $_POST['set_desc'];
$id = $my_array_of_vars['v'];
$xmlData = simplexml_load_string(file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$id}?fields=title"));
$title = (string)$xmlData->title;
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
echo "<div id='pageheader'>
1 record added<span id='logout'>Return to <a href='contributors_login.html'>Contributors Login</a></span>
</div>";
echo '<div id="setvideo"><img src="http://i4.ytimg.com/vi/'.$my_array_of_vars['v'].'/default.jpg" style="border:solid 2px white;"><p>'.$title.'</p></div>';
mysqli_close($connection);
?>
Use mysqli_real_escape_string in your INSERT INTO ... part.
You open single quotes. But the title contains also single quotes so they get closed. MySQL doesn't know this and thinks the text that follows is a MySQL keyword.
Your yourTube name has a quote in it, so the SQL line
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'
becomes this
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O'Callaghan & Gavin Sheehan - Stage 3'
which MySQL sees as
INSERT INTO videodetails SET id='null',
youtube_id='2013 Ravens Rock Rally - Jonathan O',Callaghan & Gavin Sheehan - Stage 3'
and MySQL doesn't understand Callaghan & Gavin Sheehan - Stage 3'
The case of strings that contain quotes is why mysqli_real_escape_string() exists, to find those quotes and insert a \ before them so they count as literal quote characters, instead of terminating the quoted string.
. . .
$youtube_id = mysqli_real_escape_string($my_array_of_vars['v']);
$info = mysqli_real_escape_string($connection, $_POST['set_desc']);
$sql="INSERT INTO videodetails SET id='null',youtube_id='$youtube_id',info='$title'";
if (!mysqli_query($connection,$sql))
. . .
But the best practice is to use query parameters, so you don't need to worry about those embedded quotes. Any place you have a variable in your SQL string in place of a literal value, use a query parameter placeholder. These placeholders don't work in place of table names, column names, or SQL expressions or keywords -- they only work where you would normally put a single scalar value in your SQL.
$sql="INSERT INTO videodetails SET id='null',youtube_id=?,info=?";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, 'ss', $youtube_id, $title);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
}
This is safer, and makes your SQL more readable. Notice that the ? placeholder itself doesn't go inside quotes, even if the value you bind to it is a string.
PS: I question your use of the quoted string 'null' where you may mean the SQL keyword NULL.
Your insert query is not valid sql. The keyword "set" is used with update queries. Insert queries look like this:
insert into atable
(f1, f2, etc)
values
(val1, val2, etc)
or this
insert into atable
(f1, f2, etc)
select val1, val2, etc
from someOtherTables

PHP mysql_query Syntax Error

<?php
mysql_connect("localhost","root","");
mysql_select_db("hftwmvirtualdb");
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
?>
I am trying to use posted data from an android application to trigger a query and retrieve the results from the mysql database. The Table has 4 columns, and I'm trying to retrieve the value in the third column by defining the values in the first 3 columns. Each time i clicked the button, I get the parsing error to find out my PHP script was not processing the SQL query. When running the scriptthrough the browser I get the messages:
Undefined index: Booknum in C:\wamp\www\GetVerse.php on line 4
Undefined index: Chapternum in C:\wamp\www\GetVerse.php on line 5
Notice: Undefined index: Versenum in C:\wamp\www\GetVerse.php on line 6
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND CHAPTERID = AND VERSENO =' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\GetVerse.php on line 9.
I understand i get the warning messages 1-3 is because I did not submit the post data but the latter I don't know how to fix as I have tried using the correct syntax, I tried removing "=" for "like" and that failed also. What is the problem?.
The undefined index errors are, as you specified, occurring because you did not submit the post data. This, in turn, is causing the variables $Booknum, $Chapternum, and $Versenum to be empty.
With the empty variables, the MySQL query is being generated with a WHERE clause like:
WHERE `BOOKID` = AND `CHAPTERID` = AND ...
The missing values are causing invalid MySQL, hence your error. Additionally, as you've specified (in a comment) that the POST-values are strings (and not integers which is what I would have assumed based on their usage and names), you have to wrap the values in quotes in your MySQL query too. If you do not wrap the values in quotes, even valid strings may cause the query to fail.
To fix this, try something like:
$Booknum = isset($_POST['Booknum']) ? mysql_real_escape_string(trim($_POST['Booknum'])) : null;
$Chapternum = isset($_POST['Chapternum']) ? mysql_real_escape_string(trim($_POST['Chapternum'])) : null;
$Versenum = isset($_POST['Versenum']) ? mysql_real_escape_string(trim($_POST['Versenum'])) : null;
if (!empty($Booknum) && !empty($Chapternum) && !empty($Versenum)) {
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = '" . $Booknum . "' AND `CHAPTERID` = '" . $Chapternum . "' AND `VERSENO` = '" . $Versenum . "'");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
}
This will verify that the values are properly set - if not, they will be set to null. If all three values are not empty, via PHP's empty(), your query will be executed.
This is what your SQL query will look like when the variables are substituted in:
SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = AND `CHAPTERID` = AND `VERSENO` =
When the variables contain no content (as they won't if you submit no data), the query is meaningless: the syntax is malformed.
Check whether the data is posted before doing the query. Moreover, it will also profit you to start using parameterised queries (using MySQLi or PDO) for security and convenience.
The "undefined index" messages you're getting are because those variables are not set. Check that you're actually posting those to the script.
The empty variables are why your query is wrong and you get an error.
Consider using PDO as the "mysql_" commands are deprecated. You should check your inputs before passing them to the query. isset() will work for that.
CHeck whether the Post data is coming or not, undefined index it is because, there is no data for the variables you have used. SO first verify it and then execte the SQL query.
if(isset($_POST['Booknum']) && isset($_POST['Chapternum']) && isset($_POST['Versenum']))
{
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
}
else
{
echo "No post data";
}

Categories