Some error in my mysql_fetch_assoc - php

I am trying to create a rumour-based website. In one part of the site, there is a working feature where you are post rumours and the rumours are shown.
But i am working on the homepage so that the two latest rumours are placed into a table. With my code below, there is a table with no rows, despite data being in the mysql table, and this error message:
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /websites/123reg/LinuxPackage22/th/eq/li/theqlick.com/public_html/leeds.php on line 212
Any idea? My code is below:
$query = "SELECT * FROM rumour ORDER BY id DESC";
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
echo "<table class ='rumour' border='1'>";
echo "<tr>";
echo "<td style = 'font-size:18pt;font-family:Noteworthy-Bold;'> Hot Rumours </td>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "<tr>";
echo "<td class = 'td1'>". text2link($row['description']). "</td>";
echo "</tr>";
echo "</table>";

You're posting a string into mysql_fetch_assoc, and not a mysql_query...
$query = "SELECT * FROM rumour ORDER BY id DESC";
Should be
$query = mysql_query("SELECT * FROM rumour ORDER BY id DESC");

Use are directly using $query in mysql_fetch_assoc($query) which is string type.
You forget to get result. Use this instead:
$query="Your query here";
$result=msqyl_query($query);
$row = mysql_fetch_assoc($query);

You have forget to execute you query using mysql_query function
Try this code may be help you
$query = "SELECT * FROM rumour ORDER BY id DESC";
$result=mysql_query($query);
$row = mysql_fetch_assoc($result);

The manual for that function says:
array mysql_fetch_assoc ( resource $result )
You are passing it a string containing a query, not the result of running a query.
You need to pass it through mysql_query first.
… at least you do if you continue using mysql_*, which you shouldn't. It is obsolete and you should use a modern replacement.

Related

PHP search in MySQL

I'm trying to make a search function on this website that loops through my $result_array. I've tried a bunch of different approaches on my own but to no avail. Thought it was about time I asked here. This is my code:
<?php
include 'database_info.php';
$search_string = $_POST['search1'];
$query = "SELECT * FROM customers_info WHERE first_name='$search_string'";
//Try to query the database
if($result = $data_connect->query($query)){
echo '<br /><br />Successfully sent query!<br /><br />';
}
else {
echo 'Error getting customers from the database: '.mysqli_error($data_connect).'<br />';
}
//Create Table
echo "<table id='Grid'><tr>";
echo "<th>customer_id</th>";
echo "<th>First Name</th>";
echo "<th>Last Name</th>";
echo "<th>Email</th>";
echo "<th>Country</th>";
echo "<tr>\n";
$class = "odd"; //Keep track of whether a row is equal or odd
//Loop through all the rows returned by the query, creating a table row for each
while($result_array = mysqli_fetch_assoc($result)){
echo "<tr class=\"$class\">";
echo "<td>".$result_array['customer_id']."</td>";
echo "<td><a href='view_customer.php?email=".$result_array['email']."'>" .$result_array['first_name']. "</a></td>";
echo "<td>" .$result_array['last_name']. "</td>";
echo "<td>" .$result_array['email']. "</td>";
echo "<td>" .$result_array['country']. "</td>";
echo "</td></tr>\n";
//If the last row was even make the next one odd
if($class =="odd"){
$class ="even";
}
else{
$class = "odd";
}
}
echo "</table>";
$data_connect->close();
?>
Can anybody tell me a way I could accomplish this? A function or approach I could use?
P.S.
My current approach is to alter the query, this does work but then I can only search for the customer first_name for example. I want to be able to search for email address or last_name or country. These are all columns in my database.
Your query should be like:-
$query = "SELECT * FROM customers_info WHERE (first_name LIKE '%$search_string%' OR email LIKE '%$search_string%')";
This is how your query should be:
$query = "SELECT * FROM customers_info WHERE first_name='".$search_string."';";
Should work
If your PHP loop works then it's your SQL that needs to change.
Try something like:
$search_string = str_replace(" ","|",$search_string);
$query = sprintf("SELECT * FROM customers_info WHERE (
first_name REGEXP '%s' OR
last_name REGEXP '%s' OR
email REGEXP '%s'", $search_string, $search_string, $search_string)
I prefer using sprintf but that's just a personal preference. So basically I replace any white space in your $search_query with a pipe '|'. This is so REGEXP in the SQL query can search for more than one thing e.g. search Foo Bar will now search Foo and Bar which expands your results. This is optional, however.
The query simply uses a series of OR statements so that it searches in different columns.
Hope this helps!
The most secure practice for any database related stuff, is to use the PDO.
The PDO will escape your query that will avoid SQL Injections, and moreover it is easy to fetch the details.
For example of the connetivity and fetching the data:
$db = new PDO("$type:host=localhost;dbname=x;charset=utf8","user","password");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = $db->select("SELECT * FROM customers_info WHERE first_name LIKE %:first_name%");
$query->bindParam(':first_name', $_POST['search1']);
$query->execute();
$result = $query->fetchAll();
var_dump($result);
Moreover to get it work with few attributes like email etc use for example this query:
$query = $db->select("SELECT * FROM customers_info WHERE first_name LIKE %:search% OR email LIKE %:search% OR second_name LIKE %:search%");
$query->bindParam(':search', $_POST['search1']);

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

Mysqli query multiple tables

I'm trying to make a query that then displays certain results based on previous queries
The idea is that when someone logs into the page, it gets the session username and and saves it to a variable, from there the first query selects a row based on the session username, gets that value and does the same in the second query but on a different table this time getting the row based on the result from query 1 and query 3 is same as two and then its meant to echo it out
here's the code
$con = mysqli_connect("localhost","root","","boats4u");
$search = $_SESSION['myusername'];
if(mysqli_connect_errno())
{
echo "Failed to connect to database". mysqli_connect_error();
}
$pre_res = mysqli_query($con,"SELECT ownerNo FROM boatowner WHERE email ='$search'");
$pre_res = $pre_res -> fetch_assoc();
$result = mysqli_query($con,"SELECT boatNo FROM boatforrent WHERE ownerNo ='$pre_res'");
$result = $result -> fetch_assoc();
$result2 = mysqli_query($con,"SELECT * FROM boatviewing WHERE boatNo = '$result'");
echo "<table border='1'>
<tr>
<th>Client No</th>
<th>Boat No</th>
<th>View Date</th>
<th>Comments</th>
</tr>";
while ($row = mysqli_fetch_array($result2))
{
echo "<tr>";
echo "<td>". $row['clientNo']."</td>";
echo "<td>". $row['boatNo']."</td>";
echo "<td>". $row['viewDate']."</td>";
echo "<td>". $row['comment']."</td>";
}
echo "</table>";
?>
this is what displays
Notice: Array to string conversion in
E:\Download\Xampp\htdocs\owner.php on line 29
If I remove the first query then it no errors but obviously the search doesn't work then
any help appreciated
You should do one query and also parametize the search parameter. Something along the lines like:
$stmt = $con->prepare('
SELECT boatviewing.*
FROM boatowner owner
LEFT JOIN boatforrent ON boatforrent.ownerNo = owner.ownerNo
LEFT JOIN boatviewing ON boatviewing.boatNo = boatforrent.boatNo
WHERE owner.email = ?
');
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
Such code is normally more robust against SQL injection and it's also easier in case you change your database layout.
Next to that you actually run one query instead of three which allows the database to optimize data-retrieval and keeps roundtrips between the PHP script and the database server low.

retrieve single row data in mysql using php

I created a website that has multiple logins and unique informations to it.. i want to retrieve the data from one user. example my username is qwert and my password is 1234, I want to retrieve his unique information to the database. I used the sample code in w3schools and it selects all the data but all I want to do is to retrieve the data from the user which is only logged in.
can anyone help me about this? any help will be much appreciated.
mysql_select_db("xone_login", $con);
$result = mysql_query("SELECT * FROM admin WHERE username = '$myusername' ");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['overtime'] . "</td>";
echo "<td>" . $row['daily_rate'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Replace the code in SQL in that tutorial with this (and adapt the table and column names) one:
SELECT * FROM USERS where name ='qwert' and pass = MD5('1234')
And take care at sanitizing your variables in order to avoid SQL injection attacks !
You need to use a where clause
Also you will need to specify limits on the query to restrict the result set to 1 record
$select = "SELECT * FROM usertable WHERE username = '$user' LIMIT 0, 1";
$query = mysql_query($select) or die(mysql_error());
$result = mysql_fetch_assoc($query);
//Prints the array
print_r($result);

Display only queried ID+row PHP/MySQL

I have my data stored in a MySQL table, which includes an auto_increment ID number (unique) for each new row.
I'd like users to be able to get a certain ID number, using the $_GET function.
eg. User loads http://mysite.com/id.php?id=123
Page displays ID number 123 along with the row.
echo $row['id'];
echo "<table>";
echo "<tr> <th>Unit</th> <th>Message</th> <th>Date</th> </tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr><td>";
echo $row['title'];
echo "</td><td>";
echo $row['description'];
echo "</td><td>";
echo $row['pubDate'];
echo "</td></tr>";
}
echo "</table>";
echo "</center>";
I'm stuck as to where I put the $_GET bit.
Thanks :)
You should append it to your query (using intval to avoid SQL injection) like this:
// use the id in your WHERE clause, convert it to an integer to avoid sql injections
$query = 'SELECT fields FROM table WHERE id = ' . intval($_GET['id']);
$result = mysql_query($query);
$row = mysql_fetch_row($result);
... do stuff with $row ...
Firstly, your code does not make much sense, since you use $row before it was defined.
Secondly, $result isn't defined at all, and it should be, for example like this:
$id = intval($_GET['id']);
$result = mysql_query("SELECT FROM table WHERE id = '$id'");
And now you know how and where to use $_GET['id'].
Dont waste your time doing the comparison afterwards, you'll save yourself alot of time by adding it to the original query
$id = intval($_GET['id']);
$query = "SELECT whatever FROM table WHERE id=$id";
$id = $_GET['id'];
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM `Table` WHERE `id`='" . $id . "'";
$res = mysql_query ($query);
$exist = mysql_num_rows($res);
if ($exist) {
$row = mysqlfetch_assoc($res);
...
}

Categories