I am trying to figure out what this ancient php sql code does by having it write to a text file instead of editing the sql database. This for loop is giving me major issues though. It just doesn't return anything! I think it has something to do with the curly bracket variable ${$currID}.
The $ids variable is an array of gages pulled from a website which works fine because I can echo $ids[$i]; and it returns the number of the gage.
Oh yeah, and the parts that are commented out are original parts of code that I've ommited to avoid editing the sql database. I thought it might be important to include them.
$file = fopen("test.txt","w");
$intizzler = count($ids);
for($i=0; $i<$intizzler; $i++){
//echo ($i+1) . " / " . $intizzler . ":";
$currID = $ids[$i];
${$currID} = new gage($currID);
//mysql_query("INSERT INTO gage
//(id,lng,lat,title,text,pic,datum,coords,county)VALUES(
echo fwrite($file,${$currID}->getField('id'));
echo fwrite($file,${$currID}->getField('long'));
echo fwrite($file,${$currID}->getField('lat'));
echo fwrite($file,${$currID}->getField('title'));
echo fwrite($file,${$currID}->getField('text'));
echo fwrite($file,${$currID}->getField('pic'));
echo fwrite($file,${$currID}->getField('datum'));
echo fwrite($file,${$currID}->getField('coords'));
echo fwrite($file,${$currID}->getField('county'));
//)") or die(mysql_error());
//echo "Write complete for $currID <br/>";
}
I'm completely stumped. Any help would be appreciated.
As stated in the comments when using variable variables the variable still has to resolve to a valid variable name. Try this instead:
<?php
$file = fopen("test.txt","w");
$intizzler = count($ids);
for($i=0; $i<$intizzler; $i++){
//echo ($i+1) . " / " . $intizzler . ":";
$currID = $ids[$i];
$gage = new gage($currID);
//mysql_query("INSERT INTO gage
//(id,lng,lat,title,text,pic,datum,coords,county)VALUES(
echo fwrite($file,$gage->getField('id'));
echo fwrite($file,$gage->getField('long'));
echo fwrite($file,$gage->getField('lat'));
echo fwrite($file,$gage->getField('title'));
echo fwrite($file,$gage->getField('text'));
echo fwrite($file,$gage->getField('pic'));
echo fwrite($file,$gage->getField('datum'));
echo fwrite($file,$gage->getField('coords'));
echo fwrite($file,$gage->getField('county'));
//)") or die(mysql_error());
//echo "Write complete for $currID <br/>";
}
I forgot to include a mysql_query! Now I'm able to access the code!
$result = mysql_query("select * from mytable");
It was so simple!
Related
so basically I want to make an online dictionary, the word to be searched for is introduced by an input, and I want to make so that if it can't find the word+definition in db to say a message like "We couldn't find any definition" or something like that, in my code because it can't find it , it ways "undefined variable"
<?php
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
include ("footer.php");
?>
P.S.: I know my code is vulnerable to SQLi , but I'll fix that later.
try wrapping the undefined vars in isset
if (isset($word) && isset($description)) {
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else {
echo "Nothing found";
}
Same goes for $search = $_POST['se'];
if(!isset($_POST['se'])) {
echo "Nothing found";
exit;
}
if($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
} else {
echo "$search not found";
}
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(!empty($word) && !empty($description)){
echo '<div class=\"webResult\">';
echo '<h2>$word</h2>';
echo '<p>$description</p>';
echo '</div>";
}else{
echo 'could not find your word';
}
include ("footer.php");
?>
You have to validate your variables if its have value or not
The variables $word and $description are first created inside the while loop. This means that they do not have any scope outside it. This should be the most probable cause, since you are getting a variable not defined error.
There are a couple of options here.
One, you could create these variables outside the while loop, and then assign them new values as you are doing now. Here is what your code might look like, if you choose to do it this way:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
while($row = $dictionary->fetch_assoc())
{
$word = $row['word'];
$description = $row['definition'];
}
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
This will work for you if you have multiple results in the returned mysqli_resource, and want to use the last in the list.
Two, if you are likely to get only one result returned, or if you just want to use the first result in the list, you can have the echo statement inside an if statement that checks if a valid result is returned. For example:
$search = $con->escape_string($_POST['se']);
$dictionary = $con->query("SELECT * FROM `dictionary` WHERE word = '$search'");
$word = "";
$description = "";
$row = $dictionary->fetch_assoc();
if($row)
{
$word = $row['word'];
$description = $row['definition'];
if (!empty($word) && !empty($description))
{
echo '<div class="webResult"><h2>' . $word . '</h2><p>' . $description . '</p></div>';
}
else
{
echo "We couldn't find any definition";
}
}
Note:
In the above examples, we use !empty() to check the variables. This is because isset() is pointless here, since we have already created (set) the variables ourselves.
Things to read up:
Scope of variables - http://php.net/manual/en/language.variables.scope.php
empty() function - http://php.net/manual/en/function.empty.php
Object oriented mysqli - http://php.net/manual/en/mysqli.quickstart.dual-interface.php
Try this:
include ("header.php");
$search = $_POST['se'];
include ("connect.php");
$dictionary=mysqli_query($con,"SELECT * FROM `dictionary` WHERE word = '$search'");
while($row = mysqli_fetch_array( $dictionary )) {
$word=$row['word'];
$description=$row['definition'];
}
if(isset($word)){
echo "<div class=\"webResult\">
<h2>$word</h2>
<p>$description</p>
</div>";
}
else{
echo "We couldn't find any definition";
}
include ("footer.php");
I would like to ask for some help because I am stuck at that problem. I have a MySQL DB and I am trying to create some kind of a blog system. The problem which occure to me is this:
I would like to check is there is an image tag if not not to display it. The system works perfect without images but it would be nice if I new where I messed it up. Here is my code up to now:
function outputStory($article, $only_snippet = FALSE){
global $conn;
if($article){
$sql = "SELECT ar.*, usr.name FROM cms_articles ar LEFT OUTER JOIN cms_users usr ON ar.author_id = usr.user_id WHERE ar.article_id = " . $article;
$result = mysql_query($sql, $conn);
if($row = mysql_fetch_array($result)){
echo "<h2>" . htmlspecialchars($row['title']) . "</h2>\n";
echo"<h5><div class='byLine'>От:" . htmlspecialchars($row['name']) . "</div>";
echo "<div class='pubdate'>";
if($row['is_published'] == 1){
echo date("F j, Y",strtotime($row['date_published']));
} else {
echo "No articles are published yet!";
}
echo "</div></h5>\n";
if ($only_snippet){
echo "<p>\n";
echo nl2br(trimBody($row['body']));
// I think I messed this statement alot but don't know how to make it work properly :S
if(hasPostImage() == true){
$getPostImage = "SELECT * FROM cms_images";
$getImgResult = mysql_query($getPostImage,$conn);
$rowImg = mysql_fetch_array($getImgResult);
echo"<img src='".$rowImg['img_src']."' alt='".$rowImg['img_desc']."'>";
} else {
echo '<img style="display:none">';
}
echo "</p>\n";
echo "<h4>More...</h4><br>\n";
} else {
echo "<p>\n";
echo nl2br($row['body']);
echo "</p>\n";
}
}
}
}
I hope the question is not silly or something else and thank you for the help in advance.
There are many ways for doing this, my first approach is to first check you are getting file in $_FILES is its okay then there is functions available in PHP to check file size means this will give you files size in bytes and height and width as well. File Size()
also getimagesize() if this criteria matches your criteria then proceed further
I'm making simple basketball stats plugin to wordpress, and I'm using dropdown list a lot. I wanted to make function but I don't know how to pass arguments to MySQL. Here's my code:
function dropDown($tab, $option, $text){
$result = mysqli_query($con,'SELECT * FROM tab');
while($row = mysqli_fetch_array($result)){
echo "<option value=\"";
echo $row['option'] . "\">" . $row['text'];
echo "</option><br>";
}
}
and I would like to use it like this:
dropDown("team", "team_id", "name");
I tried with different quotation marks, dots etc but it doesn't seem to work.
#edit
I know PHP syntax (some of it) and I know how to use it, but I don't know how to pass $variables to MySQL query, and that's my main problem.
try
function dropDown($team, $team_id, $name) {
// use both three var where you want
$result = mysqli_query($con,'SELECT * FROM team');
echo "<select>";
while($row = mysqli_fetch($result)){
echo "<option value=\"";
echo $row['team_id'] . "\">" . $row['name'];
echo "</option>";
}
echo "</select>";
}
dropDown("team", "team_id", "name");
I have a table
Now.i have a function in my JS
function add()
{
<?php
include('conn.php');
$rs = mysql_query("select * from position");
$row = mysql_fetch_array($rs);
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo "add2()";
?>}
function add2(){
AddAddress("<?php echo $ss;?>","<?php echo $sss;?>/<?php echo $ssss;?><br /><?php echo $sssss;?>/<?php echo $ssssss;?>");
}
How to get the every date from my table?
Something like this?
function add() {
<?php
include('conn.php');
$rs = mysql_query("select * from position");
while ( $row = mysql_fetch_array($rs) ) {
$ss=$row['Name'];
$sss=$row['nowb'];
$ssss=$row['totalb'];
$sssss=$row['nowc'];
$ssssss=$row['totalc'];
echo 'AddAddress("' . $ss . '","' . $sss . '/' . $ssss . '<br />' . $sssss . '/' . $ssssss . '");';
}
?>
}
Didn't text the echo 'AddAddress....' line so I hop eI got all the single and double quotes in the right place??
Performing POST requests using Ajax here is an example of sending data from js to php.
also stop naming your vars s,ss,sss,ssss you will have no idea what they mean when you read your code tomorrow..
and try not to use mysql_* functions they have been deprecated switch to mysqli or pdo
I got what would you like to do. In your PHP file:
function add(){
<?php
include('conn.php');
$rs = mysql_query("select * from position");
echo "var data = [] ; "
while($row = mysql_fetch_assoc($rs)){
echo "
data.push({
name: '{$row['Name']}',
nowb: '{$row['nowb']}',
totalb: '{$row['totalb']}',
nowc: '{$row['nowc']}',
totalc: '{$row['totalc']}'
}); \n\r " ;
}
?>
add2(data);
}
function add2(data){
for (var i in data){
var row = data[i] ;
AddAddress(row.name, row.nowb, row.totalb, row.nowc, row.totalc);
}
}
If I understand the question correctly you want to know how to loop through an array in php.
$row = mysql_fetch_array($rs);
foreach($row as $value){
//Do something
}
Read up on it in the docs
http://php.net/manual/en/control-structures.foreach.php
Okay I have this syntax for an UPDATE to a table in mysql inside a php script:
mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
Is there somehting wrong with it? it runs properly in my scriipt (no error's) however no updates are made even though: it is called multiple times (and has lines which match the WHERE condition) heres the entire script
<?php
$contents = file_get_contents('ted_csv.txt');
$con=mysqli_connect("localhost","root","admin","Media2net");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM ted");
$i=0;
while($row = mysqli_fetch_array($result))
{
$speaker =$row['speaker'];
$event =$row['event'];
$pattern2 = preg_quote($speaker, '/');
$pattern1 = preg_quote($event, '/');
$pattern1 = "/^.*$pattern1.*\$/m";
$pattern2 = "/^.*$pattern2.*\$/m";
if(preg_match_all($pattern1, $contents, $matches)){
$submatch = implode("\n", $matches[0]);
if (preg_match_all($pattern2, $submatch, $better)){
echo "got match" . $i . "\n";
$line =str_getcsv( $better[0][0] );
$a_bool = mysqli_query($con,"UPDATE ted SET description=$line[5]
WHERE speaker='$speaker' AND event='$event'");
if ($a_bool){
echo "got match" . $i . "\n";
}else{
echo "query unsuccesful for match" . $i . "\n";
}
}
}
$i++;
}//end of while loop results
mysqli_close($con);
?>
As you can see a match should be available as same string's $speaker and $event were pulled from table ted
So clearly there's something wrong with my syntax as for each query $a_bool is false resulting in echo "query unsuccessful for match" . $i . "\n" being called for each query . Any explanation of what I have done wrong would be greatly appreciated!
SET description=$line[5] should be in quotes
like
mysqli_query($con,"UPDATE ted SET description='{$line[5]}'
WHERE speaker='$speaker' AND event='$event'");