Loop through all items in a table mySQL - php

I'm going to use this as a cronjob, I'm trying to loop through all of the rows in a table in my database, then update each item in the the row. (I update by calling another website's API to get updated information.) I connect to the database using PDO. My code:
$loop = $dbh->prepare("SELECT * FROM item_list");
$loop->execute();
while($row = mysql_fetch_array($loop)){
...get new info and update database...
}
I have error checking on and my error is: "Warning: mysql_fetch_array() expects parameter 1 to be resource, object given in page/directory.php on line 71"
I have all the code written to update each item as it loops through, I just can't get it to loop though.

You are mixing PDO and mysql extension. Use PDO only:
while ($row = $loop->fetch()) {
...
}

$loop = $dbh->prepare("SELECT * FROM item_list");
$loop->execute();
while($row = $loop->fetch()){
...get new info and update database...
}
Try this!

Related

Why does this code only show 1 ID

I am having a problem.
I know I am using deprecated MySQL, but I am working on a website for school and security is not necessary(as long as it works). I am trying to get all the Id's from a table called Reviews. This should be stored in a array. For some reason it only shows the first one. How to get all of them stored in 1 array? This is my code which is not working:
$sql1 = "SELECT Klanten_id FROM Reviews";
$res1 = mysql_query($sql1);
$r = mysql_fetch_assoc($res1)['Klanten_id'];
1.Don't use outdated mysql_* library.Turn to mysqli_* or PDO.
2.mysql_fetch_assoc: Fetch a result row as an associative array. So you need to apply loop to get all data
Like below:-
$ids = array(); //created an array
while ($row = mysql_fetch_assoc($res1)) {
$ids[] = $row['Klanten_id']; // assign each id to the array
}
print_r($ids);// print array
3.To start working on mysqli/PDO check basic example here:- mysqli/PDO example

PHP Mysql query data not correct

I am a newbie Programmer here, I want to know why my code does not get the correct data from my Mysql DB.
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '$player'");
If I use this code, then I get the $playerbal as Resource id #7
I have found some solutions for this Resouce id #7 error. If I use mysql_fetch_array, I get just "Array"
mysql_* functions are now deprecated and shouldn't be used anymore.
Your code isn't working because you need to use mysqli_fetch_array() in order to retrieve the actual data in the table using a DB connection handler
Try using something like this :
//Create DB connection
$con=mysqli_connect("localhost","root","password","Torch");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
$result = mysqli_query($con, "SELECT money FROM table WHERE name = '$player'") or die(mysqli_error($con));
//Retrieve the info(row) from the retrieved recordset and loop through it
while($row = mysqli_fetch_array( $result )) {
//Retrieve the needed field from the row
$data=$row['money'];
//do your stuff here
}
//Close connection
mysqli_close($con);
BTW Don't forget to sanitize your inputs.
mysql_query() statement returns a resource pointer to the result set, not the data itself. You'll need to use mysql_fetch_array() in order to retrieve the actual data in the table.
here's the sol
$row = mysql_fetch_array($playerbal);
$data = $row['money'];
echo $data;
If you want to get all rows of money column then use this code-
mysql_connect('localhost',"root","password");
mysql_select_db("Torch");
$playerbal = mysql_query("SELECT money FROM table WHERE name = '{$player}'");
while($data = mysql_fetch_array($playerbal)){
echo $data[0]; //there is only one column so this column is stored into 0 index.
}

Yii-How to write this query in yii?

I am trying to fetch the no of records, but I am unable to write this query in yii. My sql query is given below.
select count(review) from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01')) . I am currently writing this query in yii is given below.
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created'>=DATE_FORMAT(NOW() ,'%Y-11-01'))
->queryAll();
But I am getting this error Fatal error: Call to undefined function NOW() in G:\www\ba.dev\protected\views\business\stats.php on line 19. I am sure it is because of my poor yii query. Kindly correct my query.
If you are willing to run the entire query and not use the active record pattern You can try built-in YII commands to do that.
$query = 'select * from post where category=:category';
$list= Yii::app()->db->createCommand($query)->bindValue('category',$category)->queryAll();
Explanation: $query should be obvious and =:category is binding the variable category dynamically to the query for security reasons. In next line I am creating the query and substituting the value of category variable by using bindValue() function, finally queryAll retrieves all the records in the database. Hope it is clear now.
In your case
$query = "select count(review) as result from review_business where (date_created>=DATE_FORMAT(NOW() ,'%Y-11-01')) and (date_created<=DATE_FORMAT(NOW() ,'%Y-12-01'))" ;
$list= Yii::app()->db->createCommand($query)->queryAll();
Now you can access the result like this:
foreach ($rows as $row) {
$result = $row["result"];
}
Try this,
$results=Yii::app()->db->createCommand()
->Select('count(review)')
->from('review_business')
->where('date_created >=DATE_FORMAT(NOW() ,"%Y-11-01")')
->queryScalar();

Obtain resource from POST php

Lets say I have a database full of info, and I want the user to find his info by inputting his ID. I collect the input of the user with:
'$_POST[PID]'
And want to put it into a resource variable like:
resource $result = '$_POST[PID]';
In order to print out their information like :
while($row = mysql_fetch_array($result))
{
echo all their information
echo "<br>";
}
However I cannot create the resource variable because it is telling me that it is a boolean. How can I fetch that resource in order to print the list?
Several problems with this
First, a resource is something like a database result set, a connection (like fsockopen), etc. You can't just declare or typecast a variable into a result set
Second, you need to do something like SQL to fetch the data based on that ID. That involves connecting to the DB, running your query and then doing your fetch_array
Third, mysql_ functions are depreciated. Consider using mysqli instead.
I think you're having problems displaying the result set.
Try this
$id = $_POST['PID'];
$result = "SELECT * FROM table WHERE id ='.$id.'";
while($row = mysqli_query($result))
{
echo $row[0]; //or whichever column you want to display.
//$row[0] will display your
// PK
}

Strange error "sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource" since ReturnDatesAsStrings

I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.

Categories