This is pretty straight forward.
EDIT: Updated question and added fourth echo.
Here is PHP code:
<?php
$ratings="3";
$item="Inception";
$query="SELECT * FROM items WHERE item = '". $item ."' LIMIT 1";
echo $query;
echo "<br />";
$result=mysql_query($query);
echo $result;
echo "<br />";
while ($row = mysql_fetch_array($result)) {
$item_id = $row['item_id'];
echo $item_id;
echo "<br />";
}
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
echo $query_two;
$sql = mysql_query($query_two);
mysql_close();
?>
Here is web output with all the echo's:
SELECT * FROM items WHERE item = 'Inception' LIMIT 1
Resource id #7
INSERT INTO ratings (rating, item_id), VALUES (' 3 ', ' ')
How come my $item_id is blank? (third row underneath Resource id)
This part of code produces it:
$result=mysql_query($query);
echo $result;
It shows Resource... because it is of resource type, it's just a sort of special handler for query, it's not like normal type (string or int for example), so it has nothing readable to print.
If you want to print data from query then you must firstly fetch it.
Also note that those mysql_* functions are deprecated, it is discouraged to use them. Note from php manual:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL
extension should be used. See also MySQL: choosing an API guide and
related FAQ for more information. Alternatives to this function
include:
mysqli_query()
PDO::query()
This does not have anything to do with IDs from the database.
This (Result#7) says that this result resource is seventh resource to be created by your php script execution.
Also
$query_two = "INSERT INTO ratings (rating, item_id), VALUES (' {$ratings} ', ' {$item_id} ')";
should be
$query_two = "INSERT INTO ratings (rating, item_id) VALUES (' {$ratings} ', ' {$item_id} ')";
You have comma before VALUES.
Also, it seems that $item_id is blank. Please check DB whether you have data for item = 'Inception'.
Regarding, Result#7 please follow others answers.
The Resource ID is coming from the actual process/object that the MySQL Query is.
to return the result you need:
$row = mysql_fetch_array( $query );
echo $row['item']
You need to do something with the result resource. Try this:
$result=mysql_query($query);
//echo $result;
$result_array = mysql_fetch_assoc( $result );
print_r( $result_array );
EDIT: I see you updated your question.
You should run your item='Inception' query directly in MySQL to confirm that results are what you expect.
You cannot echo the result that simple. You need to fetch the result to for example an array:
while ($row = mysql_fetch_array($query)) {
echo $row['a_column'] . "<br />";
}
or an object:
while ($variable = mysql_fetch_object($query) {
$value = $variable->a_column;
}
echo $value;
There are more ways but this is just two examples
Related
I get the following error:
Invalid argument supplied for foreach()
for the following code:
<?php
$connection=mysqli_connect(/*hostname*/"localhost",
/*username*/"u",
/*password*/"p",
/*database name*/"d");
try {
// Setting the query and runnin it...
$sql = "SELECT * FROM `table` WHERE `category` = 5 ORDER BY 3";
$result = $connection->query($sql);
// Iterating over the data and printing it.
foreach($result as $row) {
echo $row['rowa']. ' - '. $row['rowb']. ' - '. $row['rowc']. ' - '. $row['rowd']. ' - '. $row['rowe'].'<br />';
}
// Closing the connection.
$connection = null;
}
// Catching it if something went wrong.
catch(PDOException $e) {
echo $e->getMessage();
} ?>
How do I fix this error and is there anything else wrong with the coding?
Basically, your usage of foreach() is correct. However, it won't work with results returned by a SQL query.
Instead, you'll have to use another loop, e.g. something like this:
while ($row = function_taking_one_result($result)) {
// your own handling of $row
}
For function_taking_one_result() you've got a few built-in function calls handling the returned results in different ways (see documentation).
What you're most likely looking for is mysqli_fetch_row() which will return a PHP array using the column names as keys and the row's data as values. This function will return FALSE once there aren't any further results (and therefore leave the loop).
Use it in this way:
foreach(mysqli_fetch_array($result) as $row) {
echo $row['rowa']. ' - '. $row['rowb']. ' - '. $row['rowc']. ' - '. $row['rowd']. ' - '. $row['rowe'].'<br />';
}
EDIT:
$result = mysqli_query($connection,$sql);
if($result)
{
foreach(mysqli_fetch_array($result) as $row) {
echo $row['rowa']. ' - '. $row['rowb']. ' - '. $row['rowc']. ' - '. $row['rowd']. ' - '. $row['rowe'].'<br />';
}
}else{
echo "QUERY IS NOT OK";
}
The query() method returns an resource identifier not ARRAY. so you cant loop over non array thing. foreach loop can be used only for Arrays.
After running the query you need to fetch the data in array and then try running it on loop.
Its better if you use while() loop for db arrays.
for ex:
$sql = "SELECT * FROM `table` WHERE `category` = 5 ORDER BY 3";
$qry = $connection->query($sql); //Runs the query but wont fetch RESULT
// Iterating over the data and printing it.
while($row=$qry->fetch_array()) {
//or $qry->fetch_assoc(), $qry is the variable used to execute query. check above line
echo $row['rowa'].'-'. $row['rowb'].'-'.$row['rowc'].'-'.$row['rowd'].'-'.$row['rowe'].'<br />';
}
How can you perform a search and replace with php on an array returned from mysql_fetch_array()? If I use preg_replace() it will not return a match. Is there something that I'm missing?
This is what I have used without sucess, could anyone pleas take a look and tell me what I'm doing wrong, or possibly a better way to achive this:
mysql_connect(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD)
or die("<p>Error connecting to database: " . mysql_error() . "</p>");
mysql_select_db(DATABASE_NAME)
or die("<p>Error selecting the database " . DATABASE_NAME . mysql_error() . "</p>");
$sql = "SELECT product_id,description FROM oc_product_description WHERE product_id >= 97 AND product_id <= 100";
$result = mysql_query($sql);
$pattern = '/^.*\b([0-9]{6}\s\D\d|[0-9]{6}\s\D[0-9]{2}|[0-9]{7}\s\D[0-9]{2})\b.*$/';
$replace = '$1';
while($row = mysql_fetch_assoc($result))
{
$item[] = $row['description'];
}
foreach($item as $items)
{
echo preg_replace($pattern, $replace, $items) . '<br>';
echo '<br>';
}
all that this will do is return the same as it would without the preg_replace(). Now I know the code works because if I output a print_r($item) and copy the results into an array it works just fine. Am i doing something wrong or does preg_replace() just not work with arrays returned from mysql_fetch_assoc or mysql_fetch_array? I could put my example up where i copy the results into an array but dont want to waste space. Here is an example of an item returned from the database and the string I'm trying to match with regex. I need everything removed but the match.
One item returned from $row['description']:
1997 Suzuki VZ800 Marauder, Engine # 5506-111789, Kick stand and spring. Chrome on end is starting to chip. 0121103 S19 <img src = ">http://www.roofis27.com/motorcycle/13_01_21/103.JPG">
Here is what the regex retrurns: 0121103 S19
So therefore I have over 20,000 entry's in a database with descriptions like these and need these codes like the example above removed from them so I can INSERT them into another table column that matches the product_id relational to the descriptions product_id. I am not the best with SQL, but the <img> tag is always after the code so maybe there is a way to do it with SQL that I'm not aware of? My main concern at this point is why preg_replace() doesn't work with an array returned from mysql_fetch_array(), but works fine on any other arrays ( associative, multidimensional or not). Is there something about the values returned from a database that prevent me from being able to do this? Anything would be greatly appreciated, I'm really stuck on this!
After thinking about what jerry had to say(in the comment above) I came up with this resolution, apparently there are characters in the return from mysql_fetch_array() that are invisible and that's why the regexp does not work. I got way better results using preg_match() as follows:
$sql = 'SELECT product_id,description FROM oc_product_description';
$sql1 = 'UPDATE db_product SET model = ';
$sql2 = 'WHERE product_id = ';
$pattern = '([0-9]{6}\s\D[0-9]{2}|[0-9]{6}\s\D\d|[0-9]{7}\s\D[0-9]{2})';
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result))
{
$data[] = $row['description'];
foreach($data as $datas)
{
preg_match($pattern, $datas, $matches, PREG_OFFSET_CAPTURE);
}
foreach($matches as $match)
{
$Q1 = $sql1 . '"'. $match[0] . '"' . ' ';
}
$Q2 = $sql2 . $row['product_id'] .';';
$query = $Q1 . $Q2;
mysql_query($query);
echo 'Product ID' . $row['product_id'] . ': ';
printf("Records updated: %d\n", mysql_affected_rows());
echo '<br>';
}
Yes, I will start using PDO for database cons and querys, did some research on it and look pretty cool. It's just I'm new to php and still in school so I have so much learning going on I hate having to change ( better get used to it though, HUH?) Thank you jerry :)
I'm attempting to utilize 2 mysql tables via php/mysql 2 get me a max value. I'm assuming using an array is the correct way to do this, but I've been spending many hours and am missing something.
My tables are:
1) plantcomp, where I want to know all the CompressID listings that have a CustID of $CustID. (there are currently 3).
2) comps, where I want to use those CompressID listings to know the valid Compressor #s. I'll then do a max() on those values so I can name the next compressor max()+1.
My code attempts...This gets me an error: "Notice: Array to string conversion in (pathname) on line 55", then "Array"
//have the custid
echo $CustID;
//under table `plantcomp`, find matching compressid's.
$q55 = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
// Run query
$result55 = mysql_query($q55);
while($row = mysql_fetch_array($result55)){
echo "<p>".$row;
I also tried this, mysql_fetch_assoc, but it only gives me 2 of my 3 valid entries...
$get = mysql_query("SELECT CompressID FROM plantcomp WHERE CustID = '$CustID'");
$money = mysql_fetch_assoc($get);
while($money = mysql_fetch_assoc($get)){echo $money['CompressID'];}
Thank you in advance for your assistance!!
Please change this line
echo "<p>".$row;
to
echo "<p>";
print_r($row);
The problem you have comes from the fact that you are mixing a string (<p>) with an array ($row).
echo "<p>".$row;
You can print the $row array by using print_r:
print_r($row);
You can also access different elements of the $row array (table columns) like this:
$row['column_name'];
For example, lets say your table consists of two columns: first_name and last_name. You can print them like this:
echo '<p>' . $row['first_name'] . ' ' . $row['last_name'] . '</p>';
So, with that knowledge, we can print your CompressIDs:
$result55 = mysql_query("SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "'");
while ($row = mysql_fetch_assoc($result55))
{
echo '<p>' . $row['CompressID'] . '</p>';
}
$CompressID = array(); //Initialising an array
$query = "SELECT * FROM `plantcomp` WHERE `CustID`='" . $CustID . "' ";
$result = mysql_query($query);
while($obj = mysql_fetch_assoc($result)){
$CompressID = $obj['CompressID']; //Storing all the CompressID in an array
echo $obj['CompressID']; // sanity check
}
First run the above query and compare result with db.If the result is not matching
1)There is some wrong data in db
2)Alter your query to get desired result.
If this is working then add rest of the code
if( count($CompressID) >0 ){
$query = "SELECT max(CompressID) as maxCompressID FROM `comps` WHERE `CompressID` IN($CompressID)";
$result = mysql_query($query);
while($newObj = mysql_fetch_assoc($result){
echo $newObj['maxCompressID'];
}
}
<?php
$url = $_GET['url'];
if($url == "") {
die("Invalid Request! Missing Parameter 1!");
exit;
}
$tags = get_meta_tags($url);
$key = $tags['keywords'];
$desc = $tags['description'];
$con = mysql_connect('HOST', 'USER', 'PASS') or die(mysql_error());
mysql_select_db('zach_WebLock', $con) or die(mysql_error());
$query = "INSERT INTO `Keyword` (`Site`, `Keyword`, `Description`) VALUES ('".$site."', '".$key."', '".$desc."')";
mysql_query($query) or die(mysql_error());
echo '<b>Site: <u>'.$url.'</u></b>';
echo '<br>';
echo '<b>Description:</b>';
echo '<br>';
echo $desc;
echo '<br><br>';
$keys = explode(',', $key);
foreach($keys as $word) {
echo $word;
echo '<br>';
}
?>
This script extracts the keywords and description for the URL in the ?url= variable. It displays all the information, doesn't raise any errors but doesn't write the information to the DB. Any ideas? (
(I have left out the mysql_real_escape_string() for testing)
You're trying to insert the variable $site which is not defined. Perhaps you meant $url?
If that's not the case, please provide more information. Do you get any output from mysql_error()?
You need to add '' to allow for the AUTO INCREMENTATION for your primary key in the KeyWord table, which should stop the MySQL Error from occuring.
$query = "INSERT INTO 'Keyword' VALUES ('','$site', '$key', '$desc')";
echo $query;
If that doesn't fix your solution, I'd recommend echoing out the query when you run the script and look any blank values, fix where necessary. If you're still having issues copy paste the your expected INSERT Query that was echoed from the script and test it in PhpMyAdmin and see if you get a different result (errors).
Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}