This script is supposed to get the content of a text area and submit it to mysql, but it isnt can anyone see why?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$error = '';
$like = mysql_real_escape_string($_POST['like_box']);
mysql_query("INSERT INTO likes (like) VALUES ($like)");
$id = mysql_query("SELECT id FROM likes WHERE like=$like");
header('Location:like.php?id='.$id.'');
}?>
<form method="post" action="post.php">
<textarea name="like_box" id="like_box" style="border-style: none; border-color: inherit; border-width: 0; width: 458px; height: 65px" class="style11120"></textarea>
<tr>
<td style="height: 53px">
<div class="style11116" style="width: 417px">
<input name="Submit" type="submit" value="submit" />
</form>
Having some error reporting would tell you that you need ' around the $like and you need ` around like in the columns section, since like is a reserved word, inside the insert.
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')") or trigger_error('Query Error: ' . mysql_error());
Should work.
Also you will need to enclose the like in ` for the select:
$id = mysql_query("SELECT id FROM likes WHERE `like`=$like") or trigger_error('Query Failed: ' . mysql_error());
Your first SQL query is wrong. You have to enclose string values with quotation marks in SQL:
mysql_query("INSERT INTO likes (`like`) VALUES ('$like')");
The rest of your PHP part will not perform as you wish either. $id will be a resultset, not a value. You'll have to fetch the row like this:
$result = mysql_query("SELECT id FROM likes WHERE `like`='$like'");
$row = mysql_fetch_assoc($result);
$id = $row['id'];
Or even better, just replace the second SQL query with a call to mysql_insert_id:
$id = mysql_insert_id();
Still more possibilities for improvement:
Don't forget to call exit after you've done a header('Location: ...'); call, otherwise you may get unexpected results since the script will continue running.
Add some error handling of your insert. At least check with an if statement that it succeeded.
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given” error while trying to create a php shopping cart
I don't get it, I see no mistakes in this code but there is this error, please help:
mysql_fetch_array() expects parameter 1 to be resource problem
<?php
$con = mysql_connect("localhost","root","nitoryolai123$%^");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("school", $con);
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
?>
<?php while ($row = mysql_fetch_array($result)) { ?>
<table class="a" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#D3D3D3">
<tr>
<form name="formcheck" method="get" action="updateact.php" onsubmit="return formCheck(this);">
<td>
<table border="0" cellpadding="3" cellspacing="1" bgcolor="">
<tr>
<td colspan="16" height="25" style="background:#5C915C; color:white; border:white 1px solid; text-align: left"><strong><font size="2">Update Students</td>
<tr>
<td width="30" height="35"><font size="2">*I D Number:</td>
<td width="30"><input name="idnum" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $_GET['id']; ?>"></td>
</tr>
<tr>
<td width="30" height="35"><font size="2">*Year:</td>
<td width="30"><input name="yr" onkeypress="return isNumberKey(event)" type="text" maxlength="5" id='numbers'/ value="<?php echo $row["YEAR"]; ?>"></td>
<?php } ?>
I'm just trying to load the data in the forms but I don't know why that error appears. What could possibly be the mistake in here?
You are not doing error checking after the call to mysql_query:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
In case mysql_query fails, it returns false, a boolean value. When you pass this to mysql_fetch_array function (which expects a mysql result object) we get this error.
$id = intval($_GET['id']);
$sql = "SELECT * FROM student WHERE IDNO=$id";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
always do it this way and it will tell you what is wrong
Give this a try
$indo=$_GET['id'];
$result = mysql_query("SELECT * FROM student WHERE IDNO='$indo'");
I think this works..
The most likely cause is an error in mysql_query(). Have you checked to make sure it worked? Output the value of $result and mysql_error(). You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:
$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
die("Error running $sql: " . mysql_error());
}
Sanitizing $_GET['id'] is really important. You can use mysql_real_escape_string() but casting it to an int is sufficient for integers. Basically you want to avoid SQL injection.
Make sure that your query ran successfully and you got the results. You can check like this:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']) or die(mysql_error());
if (is_resource($result))
{
// your while loop and fetch array function here....
}
In your database what is the type of "IDNO"? You may need to escape the sql here:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
You are using this :
mysql_fetch_array($result)
To get the error you're getting, it means that $result is not a resource.
In your code, $result is obtained this way :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
If the SQL query fails, $result will not be a resource, but a boolean -- see mysql_query.
I suppose there's an error in your SQL query -- so it fails, mysql_query returns a boolean, and not a resource, and mysql_fetch_array cannot work on that.
You should check if the SQL query returns a result or not :
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if ($result !== false) {
// use $result
} else {
// an error has occured
echo mysql_error();
die; // note : echoing the error message and dying
// is OK while developping, but not in production !
}
With that, you should get a message that indicates the error that occured while executing your query -- this should help figure out what the problem is ;-)
Also, you should escape the data you're putting in your SQL query, to avoid SQL injections !
For example, here, you should make sure that $_GET['id'] contains nothing else than an integer, using something like this :
$result = mysql_query("SELECT * FROM student WHERE IDNO=" . intval($_GET['id']));
Or you should check this before trying to execute the query, to display a nicer error message to the user.
I am having trouble in getting checked values checked in form. I was trying to use the same function as I have used to insert values to print all values in edit form, and which are in other table inserted to mark them checked.
Function to insert values in database table in insert form and it works.
function emarketing_usluge(){
$link = new mysqli("localhost", "xxx", "xxx", "xxx");
$link->set_charset("utf8");
$sql=mysqli_query($link, "SELECT * FROM `jos_ib_emarketing_oprema` order by OpremaId asc ");
while($record = mysqli_fetch_array($sql)) {
echo '<input type="checkbox" name="usluge[]" value="'.$record['OpremaId ']. '">' . $record['OpremaNaziv'] . ' <br/><br/> </input>';
}
}
In this function I get list of all services and place them in checkboxes.
Now I want to edit form, and display all values that are checked by using same function.
First I make query to get values, I am using here pdo but for funcion files I have used mysqli.
Form for editing!
$sql_oprema = "SELECT a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
$oprema = $conn->query($sql_oprema);
$row = $oprema ->fetch();
<div class="col-xs-6">
<input type="checkbox" id="oprema" onclick="Exposeoprema()">Oprema<br>
<div id="Scrolloprema" style="height:150;width:200px;overflow:auto;border:1px solid blue;display:none">
<?php
while($row = $oprema ->fetch()) {
$data='<input type="checkbox" name="oprema[]" value="'.$row["Oprema"].'"';
if(isset($row['Oprema'])) {//field in the database
$data.=' checked="checked';
}
$data.='">'. $row["OpremaNaziv"] .'</br>';
}
emarketing_oprema($data);
?>
</div>
</div>
I am trying print all service values by using function, but the ones that are checked they need to have check mark. I am getting problem and could not figure it out how to solve it.
Looking back to your SQL query, I don't see an extraction of checked field, you are not selecting it. So there is never going to be a $row['checked'] element of your query.
You should add:
$sql_oprema = "SELECT a.checked, a.Partner, a.OpremaId, a.Oprema, b.OpremaNaziv
FROM jos_ib_emarketing_stavke_oprema a
join jos_ib_emarketing_oprema b
on OpremaId = b.Oprema
WHERE a.Partner= $id";
So basically I'm thinking that adding a search field to my website is out of my league, but internet has so much information that I decided to give it a go.
I started by adding a form to my index pagina, and this is the code I'm using:
<form method="get" action="search.php">
<table cellpadding="0px" cellspacing="0px">
<tr>
<td style="border-style:solid none solid solid;border-color:#4B7B9F;border-width:1px;">
<input type="text" name="q" style="width:100px; border:0px solid; height:17px; padding:0px 3px; position:relative;">
</td>
<td style="border-style:solid;border-color:#4B7B9F;border-width:1px;">
<input type="submit" value="" style="border-style: none; background: url('images/searchicon.gif') no-repeat; width: 24px; height: 19px;">
</td>
</tr>
</table>
</form>
Next up, my search.php code:
<?php
ini_set('display_errors', 0);
$search = $_GET ['q'];
mysql_connect("localhost", "root", "");
mysql_select_db("release");
$query = mysql_query("SELECT * FROM game WHERE name LIKE '%" . $queryString . "%'");
$foundnum = mysql_num_rows($query);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$foundnum results found !<p>";
$row = mysql_fetch_assoc($query);
{
echo '<p>'.$row['game_name'].'</p>';
}
}
?>
The query continuously echoes the $foundnum == 0 message even though the data I search for is in the game table.
However, when I try this code:
$query = mysql_query("SELECT game_name FROM game WHERE game_name LIKE '%" . $queryString . "%'");
The query prints '35 results found' on my screen. I have 35 entries in the database, but that doesn't make sense (to me) since I'm searching for one game name which is only entered once...
First of all you are using deprecated version mysql_* need to use mysqli_*. Please check below.
<?php
ini_set('display_errors', 2);
$search = $_GET ['q'];
// see changes from below line
$conn = mysqli_connect("localhost", "root", "","release");
$query = mysqli_query($conn,"SELECT game_name FROM game WHERE game_name LIKE '%". $search ."%'");
$foundnum = mysqli_fetch_array($query);
$count = count($foundnum['game_name']);
if ($foundnum == 0) {
echo "No results found. Either this game doesn't exist, or we have yet to add it. Please contact us!";
}
else {
echo "$count results found !<p>";
echo"<pre/>";print_r($foundnum['game_name']);
}
?>
Note:- remove include code from both index and search file that you write on upside.
From your second code it seems like there is a typo.
Try changing $query to
$query = mysql_query("SELECT * FROM game WHERE game_name LIKE '%" . $queryString . "%'");
and let me know if it works or not :)
I've ran into a wall at the moment, This code brings up a table with a button on the end of each record. Once pressed this then does a function to UPDATE the Health record by -5.
This works great for the job but it effects all rows, I've tried to get it to only touched one record via the ID but no luck! if you can help that would be great!
the php
$sql="SELECT `id` , `FirstName` , `Health` FROM ajax_demo WHERE `id` = `id` LIMIT 0 , 30";
$result = mysql_query($sql);
if(isset($_REQUEST['submit']))
{
counterminus();
}
function counterminus()
{
$cmeter = $cmeter - 1;
$id = $_POST["id"];
$FirstName = $_POST["FirstName"];
mysql_query("UPDATE ajax_demo SET `Health` = `Health` - `Damage` WHERE id = {$id}");
Header("location:oo_test.php");
}
This is the php / form
<?php
echo
"<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>health</th>
</tr>";
while($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach($row as $cell) {
echo "\n<td>$cell</td>";
}
echo '<td><form id="theForm" action="" method="POST" >
<input type="submit" name="submit" id="submit" value="Attack" />
<input type="hidden" name="'.$row[1].'" /></form></td></tr>';
echo "\n\n";
}?>
This is vunerable to attack through the $_POST['id'] variable. Use mysql_real_escape_string, or better, prepared queries through PDO or MySQLi, anyway this is orthogonal to the issue you are having, it's just a good idea to be aware of it.
You're never actually submitting a HTML form field with the name id. In addition, in your HTML, $row will be NULL outside of your while loop, so will be undefined in the first place. This will mean that the name of your hidden field will be blank, and that your SQL is saying UPDATE WHERE id=, which is invalid and will cause an error.
To fix, you need to submit a form field with the name "id" such that $_POST['id'] actually contains a value.
Why did you write {id} instead of $id ?
Plus your code is totally unsafe and could be easily altered and hacked.
You should try PDO instead of mysql_query which is also depreciated.
http://php.net/PDO
I have a form that searches a MySQL database using PHP. Currently, when a user inputs a search into one of two fields, the entire contents of the database are displayed. Also, if the user leaves both fields blank, again, the entire contents of the database will be displayed.
However, if the user inputs random information into both of the fields, then the results page will be blank.
The assumed usage of this form is that the user can search for an article based on the article's title, the article's author or organization, or the article's title and its author or organization by either filling out one or both of the fields.
What I'm trying to figure out is:
Why the results page keeps displaying all of the database contents.
and
How to ensure that the database is actually being queried rather than just being dumped by a coding error.
Code follows below:
search.php:
<div class="content">
<form id="form1" name="form1" method="post" action="searchdb.php">
<table width="100%" border="0" cellpadding="6">
<tr>
<td width="29%" align="right">Article Title:</td>
<td width="71%" align="left"><input name="articletitle" type="text" id="articletitle" size="50" /></td>
</tr>
<tr>
<td align="right">Author or Organization:</td>
<td align="left"><input name="articleorganization" type="text" id="articleorganization" size="50" /></td>
</tr>
</table>
<table width="100%" border="0" cellpadding="6">
<tr>
<td><input type="submit" name="submit" value="Submit" /></td>
</tr>
</table>
</form>
</div>
searchdb.php
<?php
include('settings.php');
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
while ($row = mysql_fetch_array($sql)){
echo '<br/> Article Title: '.$row['articletitle'];
echo '<br/> Article Organization: '.$row['articleorganization'];
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo '<td>View Full Entry</td>';
echo '<br/><br/>';
}
?>
When both are blank, your query states:
WHERE field LIKE '%%'
which matches everything.
The same happens when either one is blank, because you are using an OR to join the where clauses.
You can prevent this from happening, by checking the inputs aren't blank:
<?php
if (!((empty($_POST['field1']) || empty($_POST['field2']))) {
//run your query
}
Following on the post by #sberry.
if (isset($_POST['articletitle']) && $_POST['articletitle'] != "")
The variable can be set, but still be an empty string.
The method used by #xbonez is simpler as
if (!empty($_POST['articletitle'])) is the same as the above example that requires two tests
Have you tried xbonez method?
To be complete, this checks that at least one of the fields has been filled in:
if (!empty($_POST['articletitle']) || !empty($_POST['articleorganization'])) {
$query = "SELECT * from `articles` WHERE ";
$query .= "`articletitle` LIKE '%" . mysql_real_escape_string($_POST['articletitle']) . "%' ";
$query .= "OR `articleorganization` LIKE '%" . mysql_real_escape_string($_POST['articleorganization']) . "%'";
$sql = mysql_query($query);
} else {
// No results
}
Things that will only be used if one of the fields is filled in like:
$query = "SELECT * from `articles` WHERE ";
are placed inside the the if() statement, otherwise they are being parsed unneccesarily.
No need to create an array and then convert it into a string. ".=" will concatenate the string fragments into the final query string.
Matters of personal preference:
MySql keywords written in full caps, I find it makes the statements easier to read.
There are numerous discussions about it.
Search for "sql uppercase keywords style"
Using backticks around table and fieldnames:
Allows the use of reserved keywords for table or fieldnames (count, case, default, div, index, key, limit, option, order, etc...).
Reduces work for the mysql parser, it doesn't need to check whether there is a reserved word conflict.
Avoids problems if your table or field name becomes a reserved keyword in the future.
Again, numerous discussions. Search for "mysql backtick"
MySQLdocumentation:
9.3. Reserved Words
9.2. Schema Object Names
Look for "quoted identifier" on this page.
Also, if you might be migrating to a different database app in the future , you could use double quotes instead of backticks, look for "ANSI_QUOTES".
9.2.4. Function Name Parsing and Resolution
Look for "quoted identifier" on this page.
Tested this, and it should do exactly what you want.
$query = "select * from articles";
$where = array();
if (!empty($_POST['articletitle'])) {
$where[] = "articletitle LIKE '%".mysql_real_escape_string($_POST['articletitle'])."%'";
}
if (!empty($_POST['articleorganization'])) {
$where[] = "articleorganization LIKE '%".mysql_real_escape_string($_POST['articleorganization'])."%'";
}
if (!empty($where)) {
$query .= " WHERE " . implode(" OR ", $where);
$sql = mysql_query($query);
} else {
// No results
}
EDIT
It appears your form is passing empty values, so instead of checking isset, check !empty. I have updated the code above.